chardet 是 Python 知名的字符編碼偵測庫,能自動識別位元組串流的編碼格式(如 UTF-8、GB2312、Big5 等),適用於網頁抓取、檔案讀取等編碼未知場景。
pip install chardet
或下載原始碼安裝:python setup.py install
import chardet
result = chardet.detect(byte_data)
# 返回字典:{'encoding': 'GB2312', 'confidence': 0.99, 'language': 'Chinese'}
encoding:偵測到的編碼名稱confidence:信心度 0~1,越高越可靠language:可能的語言(僅部分編碼提供)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])
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 邊讀邊偵測,提早結束:
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。encoding="utf-8" 參數,但偵測仍需 chardet。