1

关于使用Python判断中文编码的问题

 2 years ago
source link: https://blog.moonlightwatch.com/%E4%BB%A3%E7%A0%81%E7%AC%94%E8%AE%B0/2021/03/11/%E5%85%B3%E4%BA%8E%E4%BD%BF%E7%94%A8Python%E5%88%A4%E6%96%AD%E4%B8%AD%E6%96%87%E7%BC%96%E7%A0%81%E7%9A%84%E9%97%AE%E9%A2%98.html
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

实践场景里,需要处理大量不同编码的文本文件。获得文本编码,就是一个很头疼的问题。

尝试用 chardet 解决

首先尝试了 chardet 库:

def get_encoding(file):
    # 二进制方式读取,获取字节数据,检测类型
    with open(file, 'rb') as f:
        return chardet.detect(f.read())['encoding']

对于中文,这个库有些残废。目测到的问题是:它会将 “GB2312”, “GBK”, “GB18030” 等中文编码全部认为是 “GB2312”,导致解码错误。这下好了……头更疼了……

尝试穷举编码

我的实践场景里,确定所有文件都是中文,所以我尝试使用穷举编码的方法,对文件进行解码:

def read_file(filepath:str) -> str:
    content = ""
    data=bytes()
    with open(file=filepath, mode="rb") as f:
        data = f.read()
    for encoding in ["utf-8", "utf-16", "GB2312", "GBK", "unicode", "GB18030", "Latin1"]:
        try:
            content = data.decode(encoding)
            break
        except:
            continue
    return content

大约就这样,找了比较常用的中文编码,全都试一遍即可。

目前上述编码,已经能覆盖我所有的文本文件了,如果以后有其它神奇的文件编码,再往里加吧……

网上搜索 “python 判断文本编码” 清一色的全都是用 chardet 库。或许在简单场景下,这样做没有啥问题。但是,如果是比较复杂的场景,那就应该考虑这个库的识别准确率问题。并且要根据自己的使用场景,来确定是否能接受这样的准确率。

没有完美的解决方案,还是需要在现有条件下寻找最优解……


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK