Python Unicode编码

2024-04-26 04:46:18 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在读取和解析一个Amazon XML文件,当XML文件显示a'时,当我试图打印它时,会得到以下错误:

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

从目前为止我在网上看到的情况来看,错误是由于XML文件是UTF-8格式的,但是Python希望将其作为一个ASCII编码字符处理。有没有一种简单的方法可以消除错误,让我的程序在读取XML时打印它?


Tags: 文件inamazon错误asciinotpositionrange
3条回答

很可能,您的问题是解析得很好,而现在您正试图打印XML的内容,但由于存在一些外来的Unicode字符,因此无法打印。首先尝试将unicode字符串编码为ascii:

unicodeData.encode('ascii', '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;'

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

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

assert isinstance(text, unicode) # or str on Python 3
print(text)

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

$ PYTHONIOENCODING=utf-8 python your_script.py >output.utf8

否则,python your_script.py应该按原样工作——您的语言环境设置用于对文本进行编码(在POSIX检查时:LC_ALLLC_CTYPELANG环境变量——如有必要,将LANG设置为utf-8语言环境)。

To print Unicode on Windows, see this answer that shows how to print Unicode to Windows console, to a file, or using IDLE

更好的解决方案:

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)

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

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

相关问题 更多 >