2014-01-14 35 views
0

我處理下面的XML文件:ElementTree的和UnicodeEncodeError:

<?xml version="1.0" encoding="UTF-8" standalone="no"?> 
<tag>…</tag> 

就像巨蟒文件說:

import xml.etree.cElementTree as ET 

tree = ET.parse('file.xml') 
print(tree.getroot().text) 

但不幸的是我有這樣的錯誤:

Traceback (most recent call last): 
    File "main.py", line 48, in <module> 
    print(tree.getroot().text) 
    File "C:\Python33\lib\encodings\cp852.py", line 19, in encode 
    return codecs.charmap_encode(input,self.errors,encoding_map)[0] 
UnicodeEncodeError: 'charmap' codec can't encode character '\u2026' in position 0: character maps to <undefined> 

我在做什麼這樣錯了?

+1

您的控制檯編解碼器無法處理水平省略號字符。 Elementtree正在完成它的工作,並將XML內容解碼爲Unicode值就好了。 'print()'然而需要再次*編碼*字符來匹配你的控制檯編碼,而你的Windows代碼頁不能處理這個特定的字符。 –

回答

2

請勿打印該值。處理它(你更可能要做的)將會很好地工作。

如果您確實想要打印它,請先將Unicode字符串轉換爲輸出介質可以處理的內容(例如,UTF-8編碼的字符串)。如果裏面還有奇怪的字符,你可以用它來至少休息轉換:

byteString = value.encode(sys.stdout.encoding, 'ignore') 
originalWithoutTrouble = byteString.decode(sys.stdout.encoding) 
print(originalWithoutTrouble) 

但當然,那麼一些字符可能會丟失(在這種情況下的省略號,如馬亭指出) 。