gpt4 book ai didi

python - 名称中带有 unicode 的标签和 lxml

转载 作者:行者123 更新时间:2023-11-28 23:02:17 24 4
gpt4 key购买 nike

假设我有一个在标签名称中使用 Unicode 的文档,例如 <año>2012</año> .

当我使用 lxml 中的 etree 解析此类文档时,我没有遇到任何问题,树已正确构建。但是当(为了调试目的)我尝试打印一些元素时,我得到一个异常,关于将一些 unicode 字符编码为 ASCII 的尝试失败。

这不是终端配置或文件编码错误的问题,因为我可以毫无问题地打印包含相同 unicode 字符的节点名称 ( .tag)。显然,问题是由 Element 对象的“字符串化”引起的,它假设标签名称不是纯 ascii。

下面的代码显示了问题(同时也表明不是文件/终端/编码问题)。

# coding: utf-8
from lxml import etree
doc = """<?xml version="1.0" encoding="utf-8"?>
<año>2012</año>
"""
x = etree.fromstring(doc) # No problem
print x.tag # No problem
print x # Exception

在具有正确定义的 LC_CTYPE 的终端中运行上述脚本,产生以下输出:

año
Traceback (most recent call last):
File "procesar.py", line 8, in <module>
print x
UnicodeEncodeError: 'ascii' codec can't encode character u'\xf1' in position 10: ordinal not in range(128)

注意如何 print x.tag正确输出 año .不应该print x产生类似 <Element año at b7d26eb4> 的东西?

这是一个已知问题吗?关于解决方法的任何想法?

最佳答案

在输出之前必须将unicode字符串转换为字节字符串

尝试:

print unicode(x).encode('utf8')

引用unicode function :

For objects which provide a __unicode__() method, it will call this method without arguments to create a Unicode string. For all other objects, the 8-bit string version or representation is requested and then converted to a Unicode string using the codec for the default encoding in 'strict' mode.

关于python - 名称中带有 unicode 的标签和 lxml,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10091737/

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