python讀txt亂碼解決方法:
從報(bào)錯(cuò)講起:
UnicodeDecodeError:'gbk'codeccan'tdecodebyte0xaainposition2:illegalmultibytesequence
出現(xiàn)這個(gè)錯(cuò)誤一般是由于打開(kāi)文件時(shí),沒(méi)有指定編碼引起的,比如下面代碼
withopen('../corpus.txt',mode='r')asf:
解決方法很簡(jiǎn)單,為其指定編碼就行了
withopen('../corpus.txt',encoding='utf-8',mode='r')asf:
還有一個(gè)常見(jiàn)的問(wèn)題就是,生成txt文件,查看內(nèi)容時(shí)發(fā)現(xiàn)亂碼,這可能與你在打開(kāi)文件時(shí)沒(méi)有指定編碼方式有關(guān)
代碼就像這樣
output=open('context.txt','w')
解決的方式也很簡(jiǎn)單,只要在打開(kāi)文件時(shí),指定文件編碼就行了
output=open('context.txt','w',encoding="utf-8")
以上內(nèi)容為大家介紹了python讀txt亂碼如何解決,希望對(duì)大家有所幫助,如果想要了解更多Python相關(guān)知識(shí),請(qǐng)關(guān)注IT培訓(xùn)機(jī)構(gòu):千鋒教育。