【python学习笔记】chardet模块检测编码

# -*- coding: utf-8 -*-
"""
Created on Wed Mar 18 14:16:16 2020

@author: weisssun
"""
#chardet模块可以用来检测编码
#判断位置编码的方法,是先收集各种编码的特征字符,根据特征字符的匹配进行判断
#chardet模块已经收集了这样的特征字符
#在调用该模块时,它就会将被识别数据的编码与特征字符库进行匹配,从而进行“猜测”
#因此,这样的猜测也有准确程度的问题

#参考链接:https://www.liaoxuefeng.com/wiki/1016959663602400/1183255880134144
#参考链接:https://www.jianshu.com/p/d73c0017158c

import chardet
#导入 chardet 模块

testdata = open(r'D:\Python\comment_analysis\dict\stopwords.txt', 'rb').read()
# open('文件路径', 'rb').read()
#打开要识别编码的数据
#打开测试文件,chardet 只能对 bytes 形式的编码进行检测,因此文件打开方式是 'rb'

codInf = chardet.detect(testdata)
# chardet.detect(要识别编码的数据)
#调用detect方法识别编码
print(codInf)
#输出的是字典格式的结果
#{'encoding': 'UTF-8-SIG', 'confidence': 1.0, 'language': ''}
#分别是 encoding 编码方式
#      confidence 判断编码方式的正确率
#      language 编码方式的语言( gbk 就会显示是中文)

codType = codInf['encoding']
# 字典['encoding']
#从字典中取出编码方式,传入后续的各种地方
print(codType)
print(type(codType))
#最终给出的是 str 格式的编码方式


#上述方法,chardet会全部读取文件,然后判断编码格式
#如果文件比较大,效率就会很低
#另一种方法是一行一行读取数据,将数据喂给UniversalDetector,当读取的数据足以做出判断时,就停下来

print('————————————我是分隔符————————————')
print('大文件识别编码')

from chardet.universaldetector import UniversalDetector
#导入 UniversalDetector 方法

detector = UniversalDetector()
# UniversalDetector()
#创建 UniversalDetector 方法实例 detector

bigdata = open(r'D:\Python\comment_analysis\dict\stopwords.txt', 'rb').readlines()

for line in bigdata:
    detector.feed(line)
    if detector.done:
        break
detector.close()
#一行一行读取数据,将数据喂给detector,当读取的数据足以做出判断时,就停下来

codInf2 = detector.result
print(codInf2)

codType2 = codInf2['encoding']
print(codType)

#多个文件判断编码同上
#重复调用 UniversalDetector 时,要先初始化
#UniversalDetector实例.reset()


print('————————————我是分隔符————————————')
print('多个文件识别编码')

'''
import os
from chardet.universaldetector import UniversalDetector

detector = UniversalDetector()
dirlist = os.dirlist('/Users/suosuo/Desktop/Test')
for name in dirlist:
    path = os.getcwd()+'\\%s'%name
    detector.reset()
    for line in open(path, 'rb').readlines():
        detector.feed(line)
        if detector.done: 
            break
    detector.close()
    print(detector.result)
'''


    
发布了8 篇原创文章 · 获赞 1 · 访问量 297

猜你喜欢

转载自blog.csdn.net/Sun_Weiss/article/details/104945187
今日推荐