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

标签 python unicode lxml

假设我有一个在标签名称中使用 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/

相关文章:

python - 短划线图像的模糊部分

jquery - Flask-Restful API 和 JSON 问题中的 Unicode

当您使用 xpath 知道子文本时,python lxml 获取父元素

python - 尝试运行 jupyter notebook 时模块 'attr' 中的错误

java - 为什么在 java 6 和 java 7 中获取字符 ®(U+00AE) 不同?

golang 中的字符串转换和 Unicode

python - 如何从 html 表格元素中解析文本

python - 是否可以在 Python 中针对 XSD 1.1 验证 XML 文件?

python - 在 Python 中提取和清理 HTML 正文文本的最快、最无错误的方法是什么?

python - 确定较大的月份,忽略日期