【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)
'''


    
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值