您的位置:首页 > 编程语言 > Python开发

python读取txt文件时的中文乱码问题

2017-04-06 20:10 1001 查看
今晚在做
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'
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息