gpt4 book ai didi

python - 统一码编码错误 : 'ascii' codec can't encode characters

转载 作者:太空狗 更新时间:2023-10-29 17:55:33 25 4
gpt4 key购买 nike

我有一个包含 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' 编解码器无法编码字符...

我应该如何处理这个 Unicode 字符串以使其适用于 ElementTree 解析器?

附言。请不要向我发送带有 Unicode 和 Python 解释的链接。不幸的是,我已经阅读了所有内容,但无法使用它,希望其他人可以。

最佳答案

您必须手动将其编码为 UTF-8:

ElementTree.fromstring(d[0]['data'].encode('utf-8'))

因为 API 仅将编码字节作为输入。 UTF-8 是此类数据的良好默认设置。

它将能够从那里再次解码为 un​​icode:

>>> 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 "拉柏 多公 园"

关于python - 统一码编码错误 : 'ascii' codec can't encode characters,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13493477/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com