Python - chardet


目錄

about

chardet提供自動檢測字符編碼的功能。

當我們在處理一些不規范的網頁的時候。雖然Python提供了Unicode表示的strbytes兩種數據類型,並且可以通過encode()decode()方法轉換,但是在不知道編碼的情況下,對bytesdecode()容易失敗。

對於未知編碼的bytes,要把它轉換成str,那么就需要先“猜測”編碼。猜測的方式是先收集各種編碼的特征字符,根據特征字符判斷,就能有很大概率“猜對”。

當然,我們肯定不能從頭自己寫這個檢測編碼的功能,這樣做費時費力。chardet這個第三方庫正好就派上了用場。用它來檢測編碼,簡單易用。

下載

pip install chardet

使用前需先引入。

Usage

chardet.detect

detect()函數接受一個參數,一個非unicode字符串。它返回一個字典,其中包含自動檢測到的字符編碼和從0到1的可信度級別。

response = requests.get('https://www.baidu.com')
print(chardet.detect(response.content))  # {'encoding': 'utf-8', 'confidence': 0.99, 'language': ''}

返回的字典中:

  • encoding:表示字符編碼方式。
  • confidence:表示可信度。
  • language:語言。

大文件編碼判斷

上面的例子,是一下子讀完,然后進行判斷,但這不適合大文件。

因此,這里我們選擇對讀取的數據進行分塊迭代,每次迭代出的數據喂給detector,當喂給detector數據達到一定程度足以進行高准確性判斷時,detector.done返回True。此時我們就可以獲取該文件的編碼格式。

import requests
from chardet.universaldetector import UniversalDetector

url = 'https://chardet.readthedocs.io/en/latest/index.html'

response = requests.get(url=url, stream=True)

detector = UniversalDetector()
for line in response.iter_lines():
    detector.feed(line)
    if detector.done:
        break
detector.close()
print(detector.result)  # {'encoding': 'utf-8', 'confidence': 0.99, 'language': ''}

至於response.iter_lines()不安全,我們不管,這里只是用來將數據喂給detector提高准確率。

檢測gbk

import chardet

msg = '馬上2020年奔小康,我問左手:房子、車子、票子、女人,你還有哪樣沒達標!'.encode('GBK')
print(chardet.detect(msg))  # {'encoding': 'GB2312', 'confidence': 0.99, 'language': 'Chinese'}

注意,檢測到的編碼是GB2321,relax,GBKGB2312的超集,它們同屬於一種編碼。

檢測utf-8

import chardet

msg = '左手說:你膨脹了啊?你他娘的哪樣達標了?'.encode('UTF-8')
print(chardet.detect(msg))  # {'encoding': 'utf-8', 'confidence': 0.99, 'language': ''}

檢測日文

import chardet

msg = 'おじさん、こんなふうにならないで'.encode('euc-jp')  # {'encoding': 'EUC-JP', 'confidence': 1.0, 'language': 'Japanese'}
print(chardet.detect(msg))

歡迎斧正,that's all see also: | |


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM