编码问题是一件头疼的事情,当我们在处理网络数据流时。
例如: 在解析从文件中读取的字符串, 想要将字符串统一编码为Unicode。经常会读到乱七八糟的字符串(其他国家的字符串编码)
>>> line = 'Y\x02\xd9\xea\x16\xedt\x9a\x9cs\xa0\x9a\xd2\xe0\x94\t\xfd\xff\x17O\xafj\xc3\x04\xfe\x8e\x98\xf1\x9f'
>>> type(line)
<type 'str'>
>>> line.decode("utf8")
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/home/prod/borey_zhu/borey_zhu/env/lib/python2.7/encodings/utf_8.py", line 16, in decode
return codecs.utf_8_decode(input, errors, True)
UnicodeDecodeError: 'utf8' codec can't decode byte 0xd9 in position 2: invalid continuation byte
这个时候需要知道字符串的编码, 我们可以通过 chardet 工具来完成, 可以通过 pip 进行安装, 例如:
>>> import chardet
>>> chardet.detect(line)
{'confidence': 0.32383909083254714, 'language': 'Thai', 'encoding': 'TIS-620'}
我们可以获取 该语言为 ‘Thai’(泰文), 编码为 TIS-620
>>> print line.decode("TIS-620")
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/home/prod/borey_zhu/borey_zhu/env/lib/python2.7/encodings/tis_620.py", line 15, in decode
return codecs.charmap_decode(input,errors,decoding_table)
UnicodeDecodeError: 'charmap' codec can't decode byte 0xa0 in position 10: character maps to <undefined>
>>> print line.decode("TIS-620", "ignore")
Yู๊ํtsาเ Oฏjร๑
当decode 还是会出错时, 我们可以进行添加对 undefined的character采取ignore策略
codecs.decode(obj[, encoding[, errors]])
Decodes obj using the codec registered for encoding. The default encoding is 'ascii'.
Errors may be given to set the desired error handling scheme. The default error handler is 'strict' meaning that decoding errors raise ValueError (or a more codec specific subclass, such as UnicodeDecodeError). Refer to Codec Base Classes for more information on codec error handling.
errors 参数默认是 采用 ‘strict’ 当有错误会抛出异常, 采用 ‘ignore’会对当前 character 进行忽略继续向下执行;
对上述的打印出的使用百度翻译进行验证: