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

标签 python unicode elementtree

我有一个包含 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/

相关文章:

python - 在 Pandas 数据框中保留大小为 1 >= k 的 block

python - numpy 在 tensorflow 上的 hstack 用于单个矩阵/张量

python - 使用 Fabric 构建 EC2 需要启动 Twisted 服务器至少 3 次

python - 由于 ASN1 值,提交给 IIS CA 的 CSR 失败

python - 将 xml 解析为 python 中的 pandas 数据框

python - 当同一个项目中有多个应用程序时,如何在 django 中设置 url?

linux - utf-8 文件显示双字符

sql-server - 在 SQL Server 中存储 UTF-16/Unicode 数据

python - Unicode解码错误: 'utf8' codec can't decode bytes

python - 使用 Python 将 Oracle 数据库表导出为 XML 文件?