2017-04-07 35 views
1

我試圖看看一堆stackoverflow的例子。使用無法正確編碼或解碼字符串

Python版本:Python中的字符串s 2.7.10

輸出看起來像

u'bh\xfcghi' where \xfc=ü 

我從網頁閱讀本。

我編碼經由.encode字符串之後( 'UTF-8'),它看起來像

'bh\xc3\xbcghi' where \xc3\xbc=ü 

期望輸出應爲:

bhüghi 

我甚至試圖解碼/編碼(拉丁語-1),解碼(utf-8)。

NFN尼爾評論後,我試圖再次如下:

elem.text輸出:

('elem text:', u'bh\xfcghi\nMCI\n8 90 1 0 0 2 0 0 0 0 0 0 2 26 41.4 18.5 89 14.9') 

ELEM文本類型:

('elem text type:', <type 'unicode'>) 

現在,我想打印:

splitString = elem.text.encode('utf-8').decode("utf-8").split() 
print("splitString: ", splitString[0]) 

SplitString [0]輸出:

u'bh\xfcghi' 

現在,如果我打印整個字符串拆分後:

print("splitString: ", splitString) 

SplitString輸出:

[u'bh\xfcghi', u'MCI', u'8', u'90', u'1', u'0', u'0', u'2', u'0', u'0', u'0', u'0', u'0', u'0', u'2', u'26', u'41.4', u'18.5', u'89', u'14.9'] 

的完整代碼在引擎收錄: 這裏的A link

任何幫助將不勝感激。

+0

的問題是有什麼發生,這計劃使沒有修改字符串。這不是一個編碼問題。 – Neil

+0

[Pastebin link for the fullcode](https://pastebin.com/E3PNmCbW) – Jazzy

+0

我懂了, ' splitString = unicodedata.normalize('NFKD',elem.text).encode('ascii','忽略')。split()' – Jazzy

回答

0

我得到它的工作通過使用unicodedata庫:

splitString = unicodedata.normalize('NFKD', 
elem.text).encode('ascii','ignore').split() 
0
s = u'bh\xfcghi\nMCI\n8 90 1 0 0 2 0 0 0 0 0 0 2 26 41.4 18.5 89 14.9' 
s = s.encode('utf-8') 
xs = s.split(' ') 
print(xs[0]) 

輸出:

bhüghi 
MCI 
8 

嘗試;有用。當你在終端輸入時沒有得到'預期'輸出的原因是,當你不使用print時,Python使用\ x轉義碼。

+0

這不起作用,請參閱pastebin獲取全碼訪問 – Jazzy