我正在解析一个具有“iso-8859-15”编码的 xml 文件。
像“Zürich”、“Aktienrückk”这样的词会转换为“ä ;”等等
我尝试了这些建议:
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
但我收到类似 UnicodeDecodeError: 'ascii' codec can't demodecode byte
即使这样也没有帮助
content = unicode(mystring.strip(codecs.BOM_UTF8), 'utf-8')
我在 Stack Overflow 上尝试了很多建议,但找不到我的方法。
我需要将解析的内容写回具有相同字符集(如“ü”)的 html 文件
最佳答案
试试这个:
from xml.etree import ElementTree
p = ElementTree.fromstring(u'<p>found "\u62c9\u67cf \u591a\u516c \u56ed"</p>'.encode('utf8'))
print p.text.encode('utf8')
found "拉柏 多公 园"
举个例子:
# -*- coding: utf-8 -*-
from xml.etree import ElementTree
text = 'Aktienrückk'.decode('utf8')
print text.encode('utf8')
Aktienrückk
不要忘记将 # -*-coding: utf-8 -*-
放在文件的开头。
关于python - Unicode解码错误: 'utf8' codec can't decode bytes,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18467775/