1、查看文件的编码格式
import chardet
f = open('one.txt','r')
data = f.read()
print(chardet.detect(data))
输出为:
{'confidence': 数字, 'encoding': 'utf-8'}
2、python2和3在处理字符串上的区别
<1> python2中unicode作为一种字符串类型,可使用decode是将str型转换为unicode型
type(u"a") => str型
type("a".decode('utf8')) => unicode型
<2>python3中默认所有字符串都是unicode型,不存在单独的unicode型。但存在byte型,可使用decode是将byte型转换为str型
type("a".decode('utf8')) => 报错,python3不能这样写
type(b'132') => byte型
注:
(1)print在输出时会默认其为unicode编码的字符串;
(2)可在decode时加上一个ignore;
(3)读取文本时先看其编码方式再以该种方式读取;
(4)用encode和decode完成编码格式的转换。
参考:https://www.jb51.net/article/26543.htm