概述
Python提供了Unicode表示的str和bytes兩種數(shù)據(jù)類型,并且可以通過encode()和decode()方法轉換,前提是知道哪種編碼。如果不知道,可以使用chardet來檢測編碼。安裝
pip install chardet
- 語法
import chardet
file_path = "E:\\test.txt"
with open(file_path,"rb") as obj:
data = obj.read()
file_encoding = chardet.detect(data)
print(file_encoding) # {'encoding': 'utf-8', 'confidence': 0.99, 'language': ''}
其中,encoding為檢測出的編碼,confidence為可信度, language是語言。
另外一個例子:
>>> data = '離離原上草,一歲一枯榮'.encode('gbk')
>>> chardet.detect(data)
{'encoding': 'GB2312', 'confidence': 0.7407407407407407, 'language': 'Chinese'}
檢測的編碼是GB2312,注意到GBK是GB2312的超集,兩者是同一種編碼,檢測正確的概率是74%,language字段指出的語言是'Chinese'。
注意:chardet支持檢測的編碼列表請參考官方文檔Supported encodings。