• 技术文章 >Python技术 >Python基础教程

    python chardet检测编码

    小妮浅浅小妮浅浅2021-03-17 15:01:24原创2349

    1、当我们拿到一个bytes时,就可以对其检测编码。用chardet检测编码,只需要一行代码:

    >>> chardet.detect(b'Hello, world!')
    {'encoding': 'ascii', 'confidence': 1.0, 'language': ''}

    检测出的编码是ascii,注意到还有个confidence字段,表示检测的概率是1.0(即100%)。

    2、检测GBK编码的中文

    >>> data = '离离原上草,一岁一枯荣'.encode('gbk')
    >>> chardet.detect(data)
    {'encoding': 'GB2312', 'confidence': 0.7407407407407407, 'language': 'Chinese'}

    检测的编码是GB2312,注意到GBK是GB2312的超集,两者是同一种编码,检测正确的概率是74%,language字段指出的语言是'Chinese'。

    以上就是python chardet检测编码的方法,希望对大家有所帮助。更多Python学习指路:python基础教程

    专题推荐:python chardet
    品易云
    上一篇:python pillow如何处理图像 下一篇:python psutil是什么

    相关文章推荐

    • python deque操作双向列表• python defaultdict的使用注意• Python OrderedDict怎么用• python base64是什么• python pillow如何处理图像

    全部评论我要评论

    © 2021 Python学习网 苏ICP备2021003149号-1

  • 取消发布评论
  • 

    Python学习网