这似乎是我使用了错误的函数。随着.fromstring
- 那里是没有错误消息Python:我使用.decode() - 'ascii'编解码器无法编码
xml_ = load() # here comes the unicode string with Cyrillic letters
print xml_ # prints everything fine
print type(xml_) # 'lxml.etree._ElementUnicodeResult' = unicode
xml = xml_.decode('utf-8') # here is an error
doc = lxml.etree.parse(xml) # if I do not decode it - the same error appears here
File "testLog.py", line 48, in <module>
xml = xml_.decode('utf-8')
File "/usr/lib/python2.7/encodings/utf_8.py", line 16, in decode
return codecs.utf_8_decode(input, errors, True)
UnicodeEncodeError: 'ascii' codec can't encode characters in position 89-96: ordinal not in range(128)
如果
xml = xml_.encode('utf-8')
doc = lxml.etree.parse(xml) # here's an error
或
xml = xml_
然后
UnicodeDecodeError: 'ascii' codec can't decode byte 0xd0 in position 89: ordinal not in range(128)
如果我的理解对不对:我米ust将非ASCII字符串解码为内部表示形式,然后使用这种表示形式并在发送到输出之前对其进行编码?看来我正是这样做的。
由于标头为'Accept-Charset': 'utf-8'
,输入数据必须位于非8位。
错误仍然是关于etree.parse()调用上的字符编码?什么是XML的类型? etree.parse在字符串或unicode对象上不起作用。尝试使用etree.fromstring()代替。 – hasanyasin 2012-07-08 18:06:18
@hasanyasin,看起来你是对的。 :) – 2012-07-08 18:08:24
我会写一个很好的答案,涵盖希望你会接受的两个问题是正确的答案。 :) – hasanyasin 2012-07-08 18:09:19