编码问题 UnicodeDecodeError

编码问题是一件头疼的事情,当我们在处理网络数据流时。

例如: 在解析从文件中读取的字符串, 想要将字符串统一编码为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 进行忽略继续向下执行;

对上述的打印出的使用百度翻译进行验证:
这里写图片描述

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值