编码和解码UTF-8和latin1

Lei Yu

我正在研究某人的代码来处理数据,但在此行出现了错误:

chars_sst_mangled = ['à', 'á', 'â', 'ã', 'æ', 'ç', 'è', 'é', 'í', 
'í', 'ï', 'ñ', 'ó', 'ô', 'ö', 'û', 'ü']
sentence_fixups = [(char.encode('utf-8').decode('latin1'), char) for char in chars_sst_mangled]

错误消息是

"UnicodeDecodeError: 'ascii' codec can't decode byte 0xc3 in position 0: ordinal not in range(128)"

我想知道这里有什么问题,以及如何解决?

杰夫斯

该代码已损坏。

特定错误表明您正在尝试使用python2可执行文件运行Python 3代码:

>>> 'à'.encode('utf-8')
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
UnicodeDecodeError: 'ascii' codec can't decode byte 0xc3 in position 0: ordinal not in range(128)

'à'是Python 2上的字节串,因此调用.encode()方法需要先将字节串解码为Unicode。它是做使用sys.getdefaultencoding()'ascii'在Python 2触发UnicodeDecodeError

正确的方法是删除虚假char.encode('utf-8').decode('latin1')转换并改用Unicode文字:

  • 添加正确的编码声明,例如,如果源文件是使用utf-8编码保存的,则放在# -*- coding: utf-8 -*-顶部,这样就可以正确解释源中硬编码的字符串文字中的非ascii字符
  • 另外,添加,from __future__ import unicode_literals以便'à'即使在Python 2上可以创建Unicode字符串。

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章