Python Unicode编码错误

Ale*_*x B 100 python unicode ascii encode

我正在阅读和解析Amazon XML文件,而XML文件显示',当我尝试打印它时,我收到以下错误:

'ascii' codec can't encode character u'\u2019' in position 16: ordinal not in range(128) 
Run Code Online (Sandbox Code Playgroud)

从我到目前为止在线阅读的内容来看,错误来自于XML文件是UTF-8,但Python希望将其作为ASCII编码字符处理.是否有一种简单的方法可以使错误消失并让我的程序在读取时打印XML?

Sco*_*ord 189

可能,你的问题是你解析它没关系,现在你正在尝试打印XML的内容而你不能因为有一些外来的Unicode字符.尝试首先将您的unicode字符串编码为ascii:

unicodeData.encode('ascii', 'ignore')
Run Code Online (Sandbox Code Playgroud)

'ignore'部分会告诉它只是跳过那些字符.从python文档:

>>> u = unichr(40960) + u'abcd' + unichr(1972)
>>> u.encode('utf-8')
'\xea\x80\x80abcd\xde\xb4'
>>> u.encode('ascii')
Traceback (most recent call last):
  File "<stdin>", line 1, in ?
UnicodeEncodeError: 'ascii' codec can't encode character '\ua000' in position 0: ordinal not in range(128)
>>> u.encode('ascii', 'ignore')
'abcd'
>>> u.encode('ascii', 'replace')
'?abcd?'
>>> u.encode('ascii', 'xmlcharrefreplace')
'&#40960;abcd&#1972;'
Run Code Online (Sandbox Code Playgroud)

您可能想阅读这篇文章:http://www.joelonsoftware.com/articles/Unicode.html,我发现它非常有用,作为正在发生的事情的基本教程.读完之后,你会觉得你只是猜测要使用什么命令(或者至少是发生在我身上的命令).


Pax*_*ell 15

更好的解决方案:

if type(value) == str:
    # Ignore errors even if the string is not proper UTF-8 or has
    # broken marker bytes.
    # Python built-in function unicode() can do this.
    value = unicode(value, "utf-8", errors="ignore")
else:
    # Assume the value object has proper __unicode__() method
    value = unicode(value)
Run Code Online (Sandbox Code Playgroud)

如果您想了解更多有关原因的信息:

http://docs.plone.org/manage/troubleshooting/unicode.html#id1

  • 它对OP的问题没有帮助:*"不能编码字符u'\ u2019'"*.`u'\ u2019`已经是Unicode了. (3认同)

jfs*_*jfs 5

不要在脚本中硬编码环境的字符编码; 直接打印Unicode文本:

assert isinstance(text, unicode) # or str on Python 3
print(text)
Run Code Online (Sandbox Code Playgroud)

如果您的输出重定向到文件(或管道); 你可以使用PYTHONIOENCODINGenvvar来指定字符编码:

$ PYTHONIOENCODING=utf-8 python your_script.py >output.utf8
Run Code Online (Sandbox Code Playgroud)

否则,python your_script.py将正常运行就是-你的区域设置用于将文本编码(上POSIX检查:LC_ALL,LC_CTYPE,LANGenvvars中-设置LANG,如果必要将使用UTF-8).

要在Windows上打印Unicode,请参阅此答案,该答案显示如何将Unicode打印到Windows控制台,文件或使用IDLE.