# encoding: utf-8
'''
Created on 2015年2月8日
@author: 张鹏程 aprial@163.com
@copyright: 版权所有, 尊重劳动成功, 转载与修改请注明作者
'''
import traceback
import chardet
def mytoutf8(s):
return mytounicode(s).encode('utf-8')
def mytounicode(s):
if type(s) == type(u''):
# print '1'
return s
try:
# print '2'
s = s.decode('utf-8')
except:
try:
# print '3'
s = s.decode('gb18030')
except:
print '***Error: decode string({0})'.format(repr(s))
print traceback.print_exc()
s = repr(s)
# print '4'
return s
if __name__ == '__main__':
# test 中国i love you
# utf-8
s = ur'中国i love you'
print repr(s), s
cc = ['utf-8', 'gb18030', 'gbk']
fn = [mytounicode, mytoutf8, ]
for f in fn:
for c in cc:
# print '=' * 80
print '''{0:<20}({1:10}) = {2:<50}, {3}'''.format(f.__name__, c, repr(f(s.encode(c))), f(s.encode(c)))
直接使用chardet,转码可能会得不到预期的结果。
使用中,chardet.detect()返回字典,其中confidence是检测精确度,encoding是编码形式
以下是chardet的使用方法节选自:http://www.cnblogs.com/xiaowuyi/archive/2012/03/09/2387173.html
(1)网页编码判断:
>>> import urllib
>>> rawdata = urllib.urlopen('http://www.google.cn/').read()
>>> import chardet
>>> chardet.detect(rawdata)
{'confidence': 0.98999999999999999, 'encoding': 'GB2312'}
(2)文件编码判断
import chardet
tt=open('c:\111.txt','rb')
ff=tt.readline()
#这里试着换成read(5)也可以,但是换成readlines()后报错
enc=chardet.detect(ff)
print enc['encoding']
tt.close()