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'
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'
相关文章推荐
- 解决python读取中文文件乱码问题
- FileReader读取中文txt文件编码丢失问题(乱码)(转)
- android读取txt文件中文乱码的问题
- 读取TXT文件中文乱码问题
- Python json文件读取及显示中文乱码的问题
- FileReader读取中文txt文件编码丢失问题(乱码)
- C#中读取txt文件中的中文时出现乱码问题
- python读取\t\n的文件转换成html表格发送邮件(解决中文乱码问题)
- 【JAVA】读取txt文件中文乱码问题
- 关于使用IDEA读取txt文件出现中文乱码的问题
- python读取txt解决中文乱码问题
- Andoird - 解决读取txt文件中文乱码问题
- 移动开发 - Android - 读取assets目录下的txt文件(中文乱码问题)
- Python读取中文txt乱码问题
- Python实现的json文件读取及中文乱码显示问题解决方法
- android-解决读取txt文件中文乱码问题
- Java读取properties文件中文乱码问题的解决
- windows下的txt文件传到Linux下中文乱码问题
- flex调用js写文件时,传递的参数包含中文,读取乱码问题
- android解决读取中文文件乱码的问题