源码网商城,靠谱的源码在线交易网站 我的订单 购物车 帮助

源码网商城

Python中动态检测编码chardet的使用教程

  • 时间:2022-05-21 11:25 编辑: 来源: 阅读:
  • 扫一扫,手机访问
摘要:Python中动态检测编码chardet的使用教程
[b]前言[/b] 在互联网的世界里,每个页面都使用了编码,但是形形色色的编码让我们的代码何以得知其棉麻格式呢?charset将很好的解决这个问题。 [b]1. chardet[/b] chardet是Python社区提供了一个类库包,方便我们在代码中动态检测当前页面或者文件中的编码格式信息。接口非常的简单和易用。 Project主页: [url=https://github.com/chardet/chardet]https://github.com/chardet/chardet[/url] 本地下载地址:[url=http://xiazai.jb51.net/201707/yuanma/chardet(jb51.net).rar]http://xiazai.jb51.net/201707/yuanma/chardet(jb51.net).rar[/url] 文档主页: [url=http://chardet.readthedocs.io/en/latest/usage.html]http://chardet.readthedocs.io/en/latest/usage.html[/url] [b]2. 使用示例[/b] Notice: 笔者使用的python 3.5 + [b]Case 1: 检测特定页面的编码格式[/b]
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 使用说明:[code]detect()[/code]为其关键方法 [b]Case 2: 增量检测编码格式[/b]
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'}
说明: 为了提高预测的准确性,基于[code]dector.feed()[/code]来实现持续的信息输入,在信息足够充足之后结束信息输入,给出相应的预测和判断。 如果需要复用detector方法,需要进行[code]detector.reset()[/code]进行重置,从而可以复用。 [b]Case 3: 在安装chardet之后,可以基于命令行来检测文件编码[/b]
% chardetect somefile someotherfile
somefile: windows-1252 with confidence 0.5
someotherfile: ascii with confidence 1.0
在系统层面,可以直接基于命令行来进行文件编码检测,非常简单易用。 [b]3. 总结[/b] chardet是非常易用和功能强大的Python包,相信大家在web世界中遨游之时,肯定会用上这个chardet的。 如有问题,欢迎大家反馈给我。 好了,以上就是这篇文章的全部内容了,希望本文的内容对大家的学习或者工作能带来一定的帮助,如果有疑问大家可以留言交流,谢谢大家对编程素材网的支持。
  • 全部评论(0)
联系客服
客服电话:
400-000-3129
微信版

扫一扫进微信版
返回顶部