处理编码的包。
encoding-tools的Python项目详细描述
编码工具
本模块旨在提供一个包装器来处理python中的编码。
功能
将str编码为字节
fromencoding_toolsimportTheSoCalledGreatEncoderencoder=TheSoCalledGreatEncoder()encoder.load_str('hellò')encoder.encode('latin-1')encoded_string=encoder.encoded_data
是的,这比简单的'hellò'.encode('latin-1')
复杂得多,但它处理编码错误。
默认情况下,如果遇到错误,它将回退到ascii。
fromencoding_toolsimportTheSoCalledGreatEncoderencoder=TheSoCalledGreatEncoder()encoder.load_str('cœur')# œ is not supported by latin-1encoder.encode('latin-1')encoded_string=encoder.encoded_data# equals to b'coeur'
如果要强制ascii转换,可以通过指定force_ascii=True
的
正在调用.encode()
。
将字节解码到str
fromencoding_toolsimportTheSoCalledGreatEncoder,GuessEncodingFailedExceptionencoder=TheSoCalledGreatEncoder()encoder.load_bytes(b'hell\xf2')try:encoder.decode()exceptGuessEncodingFailedExceptionase:# Deal with itraiseValueError('Wrong input...')fromedecoded_string=encoder.decoded_data# equals to 'hellò'encoding=encoder.encoding# equals to 'ISO-8859-1'
解码器将为您猜测编码使用伟大的chardet库。您也可以提供编码
如果知道何时加载数据:.load_bytes(b'hell\xf2', encoding='latin-1')
要更改数据编码,请按以下方式进行:
fromencoding_toolsimportTheSoCalledGreatEncoder,GuessEncodingFailedExceptionencoder=TheSoCalledGreatEncoder()encoder.load_bytes(b'hell\xf2')# latin-1try:encoder.decode()exceptGuessEncodingFailedExceptionase:# Deal with itraiseValueError('Wrong input...')fromeencoder.encode('utf-8')encoded_string=encoder.encoded_data# equals to b'hell\xc3\xb2'encoding=encoder.encoding# equals to 'utf-8'
路线图
- 处理解码错误
- 支持更多编码(测试套件)