天天看點

Python 讀取檔案中unicode編碼轉成中文顯示問題

Python讀取檔案中的字元串已經是unicode編碼,如:\u53eb\u6211,需要轉換成中文時有兩種方式

1.使用eval

eval("u"+"\'"+unicodestr+"\'")
           

2.使用decode:

str1 = '\u4f60\u597d'  
print str1.decode('unicode_escape')  
你好 
           

unicodestr.decode(‘unicode_escape’) # 将轉義字元\u讀取出來

‘\u’開頭就基本表明是跟unicode編碼相關的,”\u”後的16進制字元串是相應漢字的utf-16編碼。Python裡decode()和encode()為我們提供了解碼和編碼的方法。其中decode(‘unicode_escape’)能将此種字元串解碼為unicode字元串。

原創位址