Python3 要开启、读取档案时,若不是 UTF-8,会需要输入档案的语系编码,Python 会自动都转换成 UTF-8 做操作。
如下范例:(现在会遇到 Big5 的,大多数都是 Windows 的 CSV)
with open(filename, encoding='Big5') as csvline: 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'}
- CLI$ chardet filename # or $ chardetect filename (两者一样)
Python3 chardet 的程式范例
#!/usr/bin/python3 import chardet # 侦测档案编码 big5 / utf-8 def detect_file_encoding(filename): with open(filename, 'rb') as rawdata: t = chardet.detect(rawdata.read(1000)) return t['encoding'] # Big5、UTF-8-SIG、utf-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'),都可以直接操作