问题

python读取文本文件时,需要其编码参数,因此,在批量读取文本文件时,有必要检测文本文件的编码。

运行环境

Python 2.7 + chardet

使用pip安装chardet

$ pip install chardet

手动安装chardet

  • 下载chardet安装包。Python 2.7 建议安装4.0.0版本的chardet ,安装包下载地址:

https://pypi.org/project/chardet/4.0.0/
  • 将解压的安装包复制到python安装目录下的/Lib/site-package目录。如:C:\Python27\ArcGIS10.2\Lib\site-packages

  • 命令行下,进入chardet目录,运行:

$ cd C:\Python27\ArcGIS10.2\Lib\site-packages\chardet
$ python setup.py install

若提示缺少 setuptools ,则要先安装。以手动安装为例:

  • 下载setuptools安装包。Python 2.7 建议安装30.0.0版本的setuptools ,安装包下载地址:

https://pypi.org/project/setuptools/30.0.0/#files
  • 将解压的安装包复制到python安装目录下的/Lib/site-package目录。如:C:\Python27\ArcGIS10.2\Lib\site-packages

  • 命令行下,进入setuptools目录,运行:

$ cd C:\Python27\ArcGIS10.2\Lib\site-packages\setuptools
$ python setup.py install

代码

import chardet
import sys


def detect_encoding(file_path):
    """检测文件编码并返回编码类型和置信度"""
    try:
        with open(file_path, 'rb') as f:
            raw_data = f.read()
            result = chardet.detect(raw_data)
        return result['encoding'], result['confidence']
    except IOError as e:
        # 错误信息处理:将字节串异常消息转为 Unicode
        error_msg = u"file open fail: %s" % unicode(str(e), 'utf-8', 'ignore')
        print error_msg.encode(sys.stdout.encoding or 'gbk', 'replace')
        return None, None