读取一个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,这样就可以识别了。