Python之动态检测编码chardet
来源:互联网 发布:完美芦荟胶淘宝官网 编辑:程序博客网 时间:2024/05/01 14:54
引言: 在互联网的世界里,每个页面都使用了编码,但是形形色色的编码让我们的代码何以得知其棉麻格式呢?charset将很好的解决这个问题。
1. chardet
chardet是Python社区提供了一个类库包,方便我们在代码中动态检测当前页面或者文件中的编码格式信息。接口非常的简单和易用。
Project主页: https://github.com/chardet/chardet
文档主页: http://chardet.readthedocs.io/en/latest/usage.html
2. 使用示例
Notice: 笔者使用的Python 3.5 +
Case 1: 检测特定页面的编码格式
import chardet
import urllib.request
TestData = urllib.request.urlopen('http://www.baidu.com/').read()
print(chardet.detect(TestData))
输出结果:
{'confidence': 0.99, 'encoding': 'utf-8'}
结果分析, 其准确率99%的概率,编码格式为utf-8
使用说明:detect()为其关键方法
Case 2: 增量检测编码格式
import urllib.request
from chardet.universaldetector import UniversalDetector
usock = urllib.request.urlopen('http://yahoo.co.jp/')
detector = UniversalDetector()
for line in usock.readlines():
detector.feed(line)
if detector.done: break
detector.close()
usock.close()
print(detector.result)
输出结果:
{'confidence': 0.99, 'encoding': 'utf-8'}
说明: 为了提高预测的准确性,基于dector.feed()来实现持续的信息输入,在信息足够充足之后结束信息输入,给出相应的预测和判断。
如果需要复用detector方法,需要进行detector.reset()进行重置,从而可以复用。
Case 3: 在安装chardet之后,可以基于命令行来检测文件编码
% chardetect somefile someotherfile
somefile: windows-1252 with confidence 0.5
someotherfile: ascii with confidence 1.0
在系统层面,可以直接基于命令行来进行文件编码检测,非常简单易用。
3. 总结
chardet是非常易用和功能强大的Python包,相信大家在web世界中遨游之时,肯定会用上这个chardet的。 如有问题,欢迎大家反馈给我。
欢迎大家关注我的头条号: 程序加油站
- Python之动态检测编码chardet
- Python字符编码检测 -- chardet
- python编码检测模块chardet
- Python之检测文件的字符编码(chardet)
- python字符编码检测——chardet
- python chardet模块 检测文档编码
- Python使用chardet检测字符编码
- Python编码检测 chardet 效果不如 UnicodeDammit
- Python基础 检测多种语言编码 chardet
- 01-chardet编码检测
- 17.python字符编码检测——chardet
- 如何用Python中的chardet去检测字符编码类型
- Python chardet 字符编码判断
- python-字符编码库chardet
- Python chardet 字符编码判断
- python chardet模块查看编码
- [python3.x] 利用chardet检测网页编码
- python2.7:文件编码检测chardet 详解
- 线程与线程类
- GPS工作原理
- JAVA相关基础知识
- [整理]PHP/HTML混写的四种方式
- 1040. 有几个PAT(25)----暴力
- Python之动态检测编码chardet
- 23.Merge k Sorted Lists
- AndroidStudio动态调试apk
- SSM/angularjs _ 文件的上传下载
- codeforces 285E. Positions in Permutations (容斥原理+DP)
- JProfiler之java剖析工具
- 在Android Studio中进行UI测试
- java中的阻塞线程
- 您的设计模式——建造者模式【Builder Pattern】