假设我有一个在标签名称中使用 Unicode 的文档,例如 <año>2012</año>
.
当我使用 lxml 中的 etree 解析这样的文档时,没有任何问题,树已正确构建。但是,当(出于调试目的)我尝试打印一些元素时,我收到一个异常,即尝试将某些 unicode 字符编码为 ASCII 失败。
不是终端配置问题或文件编码错误,因为我可以毫无问题地打印节点的名称( .tag
),其中包含相同的 unicode 字符。显然,问题是由 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/