Python study----------第三方module-----chardet(识别编码)

chardet是character detct 字符检测的缩写

gb18030是最新的标准,兼容性最好

eg1:

>>> import chardet#导入模块
>>> import os#导入os模块
>>> os.getcwd()#获取当前路径
'C:\Users\Administrator\AppData\Local\Programs\Python\Python38-32'
>>> os.chdir(d:)#改变当前路径,因为示例中的txt文档存放在d盘中
>>> os.getcwd()#获取当前路径
'D:\'
>>> file = '123.txt'
>>> with open (file,'rb') as f:
      s = f.read()#将文件中的内容一次读入变量s

>>> d = chardet.detect(s)#检测
>>> print(d)
{'encoding': 'ascii', 'confidence': 1.0, 'language': ''}
>>>

编码保存在一个字典中,其中confidence表示置信度,也就是可靠程度。

eg2:如果文件是莫名文件可以尝试使用一下代码,提前判断

    >>> file = '123.txt'
    >>> with open (file,'rb') as f:
    s = f.read()

    >>> d = chardet.detect(s)
    >>> e = d['encoding']
    >>> if e.lower().startswith('gb'):  #先把e所有的字母改为小写,然后判断是否以指定字符开头
    e = 'gb18030'

    >>> with open (file,encoding = e ) as f:
    s = f.readlines()

    >>> for i in s:
    print(i)

未完待续....

余生山海远阔,愿你随心所向,随梦所往,随爱所去
原文地址:https://www.cnblogs.com/yigexiaozuanfeng/p/13513803.html