zoukankan      html  css  js  c++  java
  • Python判断字符串编码以及编码的转换

    判断字符串编码

    使用 chardet 可以很方便的实现字符串/文件的编码检测。尤其是中文网页,有的页面使用GBK/GB2312,有的使用UTF8,如果你需要去爬一些页面,知道网页编码很重要

    >>> import urllib
    >>> html = urllib.urlopen('http://www.chinaunix.net').read()
    
    >>> import chardet
    >>> chardet.detect(html)
    {'confidence': 0.98999999999999999, 'encoding': 'GB2312'}

    函数返回值为字典,有2个元素,一个是检测的可信度,另外一个就是检测到的编码。

    编码转换

    先把其他编码转换为unicode再转换其他编码, 如utf-8转换为gb2312

    >>> import chardet
    >>> str = "我们"
    >>> print(chardet.detect(str))
    {'confidence': 0.7525, 'encoding': 'utf-8'}
    
    >>> str1 = str.decode('utf-8')
    
    >>> str2 = str1.encode('gb2312')
    >>> print(chardet.detect(str2))
    {'confidence': 0.8095977270813678, 'encoding': 'TIS-620'}
    
  • 相关阅读:
    组件基础
    css 手稿
    HTML手稿
    Vmstat命令监控Linux资源并将数据通过图形化方式显示
    JAVA---类和对象
    JAVA---Graphics2D类
    JAVA---数组
    JAVA---图形处理
    JAVA----日历源代码
    SQL常用语句大全
  • 原文地址:https://www.cnblogs.com/zhanhg/p/4392089.html
Copyright © 2011-2022 走看看