1. 程式人生 > >Python學習筆記__13.3章 chardet

Python學習筆記__13.3章 chardet

編程語言 Python

# 這是學習廖雪峰老師python教程的學習筆記


對於未知編碼的bytes,要把它轉換成str,就需要知道該bytes的編碼方式。我們可以用chardet這個第三方庫來檢測編碼

1)直接檢測bytes

>>> chardet.detect(b'Hello, world!')

{'encoding': 'ascii', 'confidence': 1.0, 'language': ''}

檢測出的編碼是ascii,confidence字段,表示檢測的概率是1.0(即100%)

2)檢測GBK

編碼的中文

>>> data = '離離原上草,一歲一枯榮'.encode('gbk')

>>> chardet.detect(data)

{'encoding': 'GB2312', 'confidence': 0.7407407407407407, 'language': 'Chinese'}

檢測的編碼是GB2312,註意到GBK是GB2312的超集,兩者是同一種編碼,檢測正確的概率是74%,language字段指出的語言是'Chinese'。

s1是s2的超集

技術分享圖片

3、擴展文檔

chardet支持檢測的編碼列表 (https://chardet.readthedocs.io/en/latest/supported-encodings.html)


Python學習筆記__13.3章 chardet