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'



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值