美文网首页
2019-09-21 读取中文乱码

2019-09-21 读取中文乱码

作者: spiderzzZ | 来源:发表于2019-10-08 10:50 被阅读0次

读取一个txt文档的时候,里面有中文就会导致中文出现乱码,

1. 查看文档格式

with open(path,'r')as f:

    text = f.read().encode()

    print(chardet.detect(text))

结果:{'encoding': 'utf-8', 'confidence': 0.87625, 'language': ''}显示是utf-8编码

2.此时直接输出text

i:\xe7\xbb\x94\xe6\xac\x93\xe6\x9a\xb1

from: AUTO

可以看到,i后面的中文变成了二进制编码格式,需要如下:

with open(path,'r')as f:

text = f.read()

# print(chardet.detect(text))

    text = text.encode('gbk')

    text = text.decode('utf-8')

    print(text)

大概就是先将他通过gbk转换一下格式,然后在转换为utf-8,这样就可以识别了。

相关文章

网友评论

      本文标题:2019-09-21 读取中文乱码

      本文链接:https://www.haomeiwen.com/subject/xeheuctx.html