1. 安裝chardet
在命令行中,進入Python27\Scripts目錄,輸入以下的命令:easy_install chardet
2. 操作
import chardet f = open('file','r') fencoding=chardet.detect(f.read()) print fencoding
fencoding輸出格式 {'confidence': 0.96630842899499614, 'encoding': 'GB2312'} ,只能判斷是否為某種編碼的概率。比較准確的結果了。輸入參數為str類型。
備注:
- str利用decode方法根據str的編碼將其解碼為unicode字符串類型
- str利用encode根據特定的編碼將unicode字符串類型轉換為特定的編碼