Python Unicode编码错误
我正在读取和解析Amazon XML文件,并且当XML文件显示’时,尝试打印该文件时,出现以下错误:
'ascii' codec can't encode character u'\u2019' in position 16: ordinal not in range(128)
从到目前为止的在线阅读中,该错误是由于XML文件位于UTF-8中引起的,但是Python希望将其作为ASCII编码字符来处理。有没有一种简单的方法可以使错误消失并让我的程序在读取时打印XML?
-
可能是,您的问题是您已对其进行了解析,现在您正尝试打印XML的内容,但由于存在一些外来Unicode字符而无法这样做。首先尝试将unicode字符串编码为ascii:
unicodeData.encode('ascii', 'ignore')
“忽略”部分将告诉它只跳过那些字符。从python文档中:
>>> # Python 2: u = unichr(40960) + u'abcd' + unichr(1972) >>> u = chr(40960) + u'abcd' + chr(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') 'ꀀabcd޴'
您可能需要阅读这篇文章:http :
//www.joelonsoftware.com/articles/Unicode.html,我发现它对于发生的事情是非常有用的基础教程。阅读之后,您将不再觉得自己只是在猜测要使用的命令(或者至少是我遇到的命令)。