今晚在做
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'