python判断字符编码

1
2
3
4

import sys
reload(sys)
sys.setdefaultencoding('utf-8')

Python 字符编码判断

法一

1
2
3
4
5
6
7
8

#判断是否为一般字符串

isinstance(s, str)

#用来判断是否为unicode

isinstance(s, unicode)

1
2
if type(str).__name__  != "unicode":
str=unicode(str, "utf-8")

法二:

Python chardet 字符编码判断
使用 chardet 可以很方便的实现字符串/文件的编码检测。尤其是中文网页,有的页面使用GBK/GB2312,有的使用UTF8,如果你需要去爬一些页面,知道网页编码很重要的,虽然HTML页面有charset标签,但是有些时候是不对的。那么chardet就能帮我们大忙了。

1
2
3
4
5
6

import urllib

import chardet
rawdata = urllib.urlopen('http://www.google.cn/').read()
chardet.detect(rawdata)

Results:

1
2

{'confidence': 0.98999999999999999, 'encoding': 'GB2312'}

chardet可以直接用detect函数来检测所给字符的编码。

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