Python判断字符串、文件字符编码

本段工具代码用于判断字符串或者文本文件的字符编码类型,可以识别常用的UTF-8,UTF-8-SIG,UTF-16,GBK,GB2312 ,GB18030 ,ASCII字符编码格式,如果有特殊字符集需求,可以扩充字符编码列表。

代码如下:

[charset.py]

# this util is used to detect file or string bytes encoding
# author: lixk
# email: 1749498702@qq.com

# info: UTF includes ISO8859-1,GB18030 includes GBK,GBK includes GB2312,GB2312 includes ASCII
CODES = ['UTF-8', 'UTF-16', 'GB18030', 'BIG5']
# UTF-8 BOM prefix
UTF_8_BOM = b'\xef\xbb\xbf'


def detect(s):
    """
    get file encoding or bytes charset

    :param s: file path or bytes data

    :return: encoding charset
    """

    if type(s) == str:
        with open(s, 'rb') as f:
            data = f.read()
    elif type(s) == bytes:
        data = s
    else:
        raise TypeError('unsupported argument type!')

    # iterator charset
    for code in CODES:
        try:
            data.decode(encoding=code)
            if 'UTF-8' == code and data.startswith(UTF_8_BOM):
                return 'UTF-8-SIG'
            return code
        except UnicodeDecodeError:
            continue
    raise UnicodeDecodeError('unknown charset!')

detect方法用于判断文件或者字节列表编码类型,参数为文件路径或者字节列表bytes

使用示例:

import charset

print(charset.detect('abc哈哈'.encode('gbk')))
print(charset.detect('test.txt'))
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值