[英]UnicodeEncodeError: 'ascii' codec can't encode characters
I have a dict that's feed with url response. 我有一个dict,它是url响应的feed。 Like: 喜欢:
>>> d
{
0: {'data': u'<p>found "\u62c9\u67cf \u591a\u516c \u56ed"</p>'}
1: {'data': u'<p>some other data</p>'}
...
}
While using xml.etree.ElementTree
function on this data values ( d[0]['data']
) I get the most famous error message: 在此数据值( d[0]['data']
)上使用xml.etree.ElementTree
函数时,我得到了最着名的错误消息:
UnicodeEncodeError: 'ascii' codec can't encode characters...
What should I do to this Unicode string to make it suitable for ElementTree parser? 我应该怎么做这个Unicode字符串,使其适合ElementTree解析器?
PS. PS。 Please don't send me links with Unicode & Python explanation. 请不要向我发送带有Unicode和Python解释的链接。 I read it all already unfortunately, and can't make use of it, as hopefully others can. 我已经很遗憾地阅读了这一切,并且无法利用它,希望其他人可以。
You'll have to encode it manually, to UTF-8: 你必须手动编码为UTF-8:
ElementTree.fromstring(d[0]['data'].encode('utf-8'))
as the API only takes encoded bytes as input. 因为API仅将编码字节作为输入。 UTF-8 is a good default for such data. UTF-8是此类数据的良好默认值。
It'll be able to decode to unicode again from there: 它将能够从那里再次解码为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 "拉柏 多公 园"
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.