這似乎是我使用了錯誤的函數。隨着.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