1. 程式人生 > >python讀取txt檔案時的中文亂碼問題

python讀取txt檔案時的中文亂碼問題

今晚在做

https://github.com/Yixiaohan/show-me-the-code

上的python小練習0011題時,一直出現以下‘utf-8’無法decode的問題:

utf8' codec can't decode byte 0xb1 in position 0: invalid start byte

即使我借鑑

http://stackoverflow.com/questions/12468179/unicodedecodeerror-utf8-codec-cant-decode-byte-0x9c

中errors = ‘replace’的形式,雖然錯誤沒有了,但訓練目標卻也達不到。

摸索了很長世間,最後還是用gb18030編碼解決了問題,只是原因尚不自知,在此附上程式碼,下次若出現類似問題,多用幾種編碼形式試試。

__author__ = 'moon.d.carl'
# -*- coding:'utf-8' -*-
#敏感詞文字檔案 filtered_words.txt,裡面的內容為以下內容,當用戶輸入敏感詞語時,則打印出 Freedom,否則打印出 Human Rights。

import sys

reload(sys)
sys.setdefaultencoding('utf-8')


path = 'E:/python_practise_material/0011.txt'

filtered_words = [words.strip('\n').decode('gb18030') for words in open(path, 'r')]

input_word = raw_input()

print 'Freedom' if unicode(input_word, 'gb18030') in filtered_words else 'Human Rights'