我有一个带有url响应的字典。像这样:
>>> d
{
0: {'data': u'<p>found "\u62c9\u67cf \u591a\u516c \u56ed"</p>'}
1: {'data': u'<p>some other data</p>'}
...
}在对此数据值(d[0]['data'])使用xml.etree.ElementTree函数时,我得到了最著名的错误消息:
UnicodeEncodeError: 'ascii' codec can't encode characters...
我应该对这个Unicode字符串做些什么才能使它适合ElementTree解析器?
PS。请不要发送给我与Unicode和Python解释链接。不幸的是,我已经全部读完了,并且不能使用它,希望其他人可以使用它。
发布于 2012-11-21 20:46:53
您必须手动将其编码为UTF-8:
ElementTree.fromstring(d[0]['data'].encode('utf-8'))因为API只接受编码的字节作为输入。对于这样的数据,UTF-8是一个很好的默认值。
它将能够从那里再次解码为unicode:
>>> from xml.etree import ElementTree
>>> p = ElementTree.fromstring(u'<p>found "\u62c9\u67cf \u591a\u516c \u56ed"</p>'.encode('utf8'))
>>> p.text
u'found "\u62c9\u67cf \u591a\u516c \u56ed"'
>>> print p.text
found "拉柏 多公 园"https://stackoverflow.com/questions/13493477
复制相似问题