首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> C語言 >> C++ >> 關於C++

Python chardet 庫:字符編碼自動檢測實戰指南

     編輯:關於C++

安裝與基本用法

pip install chardet

chardet.detect(bytes) 返回字典:{'encoding': 'utf-8', 'confidence': 0.99, 'language': ''}。

檢測網頁編碼示例

import urllib.request
import chardet

url = 'https://www.baidu.com'
response = urllib.request.urlopen(url)
html_bytes = response.read()
result = chardet.detect(html_bytes)
print(f"編碼: {result['encoding']}, 置信度: {result['confidence']}")

封裝通用函數

def get_charset(url: str) -> str:
    """自動獲取網頁字符集"""
    try:
        with urllib.request.urlopen(url, timeout=10) as resp:
            content = resp.read()
        return chardet.detect(content)['encoding']
    except Exception as e:
        print(f"檢測失敗: {e}")
        return 'utf-8'  # 默認回退

if __name__ == '__main__':
    sites = ['https://www.csdn.net/', 'https://www.imooc.com/', 'https://www.51cto.com/']
    for site in sites:
        print(f"{site} -> {get_charset(site)}")

進階用法

  • 檢測字符串/文件:同樣調用 detect(bytes_data)。
  • 批量處理:對大量文件編碼未知時,可先掃描前幾 KB 加速。
  • 置信度閾值:生產環境建議檢查 confidence > 0.8 才信任結果,否則回退默認編碼。

常見問題

  1. 短文本檢測不準:需足夠字節樣本(建議 > 1KB)。
  2. 中文編碼區分:GB2312/GBK/GB18030 常被統一識別為 GB2312,實際處理時可統一用 GB18030 解碼。
  3. Python 3 字符串為 Unicode,網絡/文件讀取得到的是 bytes,直接傳給 detect 即可。
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved