Python 判斷檔案的語系編碼 UTF-8、Big5

Python3 要開啟、讀取檔案時,若不是 UTF-8,會需要輸入檔案的語系編碼,Python 會自動都轉換成 UTF-8 做操作。

如下範例:(現在會遇到 Big5 的,大多數都是 Windows 的 CSV)

  1. with open(filename, encoding='Big5') as csvline:
  2. rows = csv.reader(csvline, delimiter=',')

但是有些來源是 Big5、有些是 UTF-8,就需要偵測語系編碼,要怎麼做呢?

Python 判斷檔案的語系編碼 UTF-8、Big5

Python 可以使用 chardet 來抓取文字編碼,所以要判斷檔案編碼,需要抓一小段文字給他

  • Python3 的 chardet 安裝:pip3 install chardet
    • CLI$ chardet filename # or $ chardetect filename (兩者一樣)
      • filename: UTF-8-SIG with confidence 1.0
    • 簡易範例
      • import chardet
      • chardet.detect('string...') # {'confidence': 1.0, 'encoding': 'ascii'}

Python3 chardet 的程式範例

  1. #!/usr/bin/python3
  2. import chardet
  3. # 偵測檔案編碼 big5 / utf-8
  4. def detect_file_encoding(filename):
  5. with open(filename, 'rb') as rawdata:
  6. t = chardet.detect(rawdata.read(1000))
  7. return t['encoding'] # Big5、UTF-8-SIG、utf-8
  8. print(detect_file_encoding(filename)) # Big5、UTF-8-SIG、utf-8 ...
  • 在這範例程式裡面,看到 Big5、utf-8 都很容易懂,但是 UTF-8-SIG 是什麼?
    • UTF-8-SIG:檔案有 BOM 開頭的,就會是這個編碼
    • 這些編碼可以直接丟進去 open(filename, encoding='UTF-8-SIG'),都可以直接操作

作者: Tsung

對新奇的事物都很有興趣, 喜歡簡單的東西, 過簡單的生活.

發表迴響

這個網站採用 Akismet 服務減少垃圾留言。進一步了解 Akismet 如何處理網站訪客的留言資料