萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 網路程式設計 >> 程式語言綜合

Python 字符編碼偵測:chardet 庫安裝與使用詳解

chardet 是 Python 知名的字符編碼偵測庫,能自動識別位元組串流的編碼格式(如 UTF-8、GB2312、Big5 等),適用於網頁抓取、檔案讀取等編碼未知場景。

安裝方式

pip install chardet

或下載原始碼安裝:python setup.py install

核心 API:detect()

import chardet
result = chardet.detect(byte_data)
# 返回字典:{'encoding': 'GB2312', 'confidence': 0.99, 'language': 'Chinese'}
  • encoding:偵測到的編碼名稱
  • confidence:信心度 0~1,越高越可靠
  • language:可能的語言(僅部分編碼提供)

實戰範例 1:網頁編碼偵測

import urllib.request
import chardet

url = 'https://www.google.cn/'
with urllib.request.urlopen(url) as resp:
    raw = resp.read()

detected = chardet.detect(raw)
print(detected)
# {'encoding': 'GB2312', 'confidence': 0.99, 'language': 'Chinese'}

# 正確解碼
html = raw.decode(detected['encoding'])
print(html[:200])

實戰範例 2:本地檔案編碼偵測

import chardet

def detect_file_encoding(filepath, sample_size=1024):
    '''讀取前 sample_size 位元組偵測編碼,避免大檔案記憶體壓力'''
    with open(filepath, 'rb') as f:
        raw = f.read(sample_size)
    return chardet.detect(raw)

enc = detect_file_encoding('data.txt')
print(f"Encoding: {enc['encoding']}, Confidence: {enc['confidence']:.2%}")

# 完整讀取並解碼
with open('data.txt', 'r', encoding=enc['encoding'], errors='replace') as f:
    content = f.read()

進階:UniversalDetector 串流偵測

對於超大檔案,可使用 UniversalDetector 邊讀邊偵測,提早結束:

from chardet.universaldetector import UniversalDetector

def detect_large_file(filepath):
    detector = UniversalDetector()
    with open(filepath, 'rb') as f:
        for line in f:
            detector.feed(line)
            if detector.done:
                break
    detector.close()
    return detector.result

print(detect_large_file('huge.log'))

常見編碼對照

編碼名稱適用場景備註
UTF-8現代網頁、國際化檔案無 BOM 時偵測較難,confidence 可能較低
GB2312 / GBK / GB18030中文簡體網頁、舊系統檔案chardet 常回傳 GB2312 代表 GBK 系
Big5中文繁體網頁含 Big5-HKSCS 擴展
ISO-8859-1西歐語言單位元組編碼
Shift_JIS日文需區分 CP932

注意事項

  • 偵測準確度取決於樣本大小與特徵明顯度,短字串易誤判。
  • confidence < 0.5 時建議人工確認或嘗試常見編碼 fallback。
  • Python 3.11+ 內建 encoding="utf-8" 參數,但偵測仍需 chardet。
copyright © 萬盛學電腦網 all rights reserved