朱金华 20130223
近期写了几个小脚本, 涉及到字符编码的时候总是失败, 无规律可循, 最后总结如下:
[1]文件里面引号括起来的字符串其编码与脚本文件编码一致.
若源文件为utf-8, 则str='朱金华'的编码为utf-8
对字符的处理一般都是先decode(当前编码) 使之变为unicode, 然后再encode(目标编码的)
[2]print打印, 这个显示中文字符需要与控制台编码一致. 譬如windows cmd默认是gbk的, 那么只有按照gbk或gb2312编码的才能显示
rawstr='zjh123朱金华'
print rawstr,repr(rawstr),type(rawstr)
str=rawstr.decode('utf-8').encode('utf-8')
print str,repr(str),type(str)
str=rawstr.decode('utf-8')
print str,repr(str),type(str)
str=rawstr.decode('utf-8').encode('gbk')
print str,repr(str),type(str)
print'----------------------------------------------'
rawstr=u'zjh123朱金华'
print rawstr,repr(rawstr),type(rawstr)
str=rawstr.encode('utf-8')
print str,repr(str),type(str)
str=rawstr
print str,repr(str),type(str)
str=rawstr.encode('gbk')
print str,repr(str),type(str)
输出: cmd位GBK编码
zjh123鏈遍噾鍗?'zjh123\xe6\x9c\xb1\xe9\x87\x91\xe5\x8d\x8e' <type 'str'>
zjh123鏈遍噾鍗?'zjh123\xe6\x9c\xb1\xe9\x87\x91\xe5\x8d\x8e' <type 'str'>
zjh123朱金华 u'zjh123\u6731\u91d1\u534e' <type 'unicode'>
zjh123朱金华 'zjh123\xd6\xec\xbd\xf0\xbb\xaa' <type 'str'>
----------------------------------------------
zjh123朱金华 u'zjh123\u6731\u91d1\u534e' <type 'unicode'>
zjh123鏈遍噾鍗?'zjh123\xe6\x9c\xb1\xe9\x87\x91\xe5\x8d\x8e' <type 'str'>
zjh123朱金华 'zjh123\xd6\xec\xbd\xf0\xbb\xaa' <type 'str'>
总结:
rawstr='zjh123朱金华'
print rawstr,repr(rawstr),type(rawstr)
str=rawstr.decode('utf-8').encode('utf-8')
print str,repr(str),type(str) #这两个的编码是一致的, 也说明原先就是utf-8编码的 'zjh123\xe6\x9c\xb1\xe9\x87\x91\xe5\x8d\x8e' print显示乱码
str=rawstr.decode('utf-8')
print str,repr(str),type(str) # #按当前编码utf-8解码后得到 unicode u'zjh123\u6731\u91d1\u534e' <type 'unicode'>
str=rawstr.decode('utf-8').encode('gbk')
print str,repr(str),type(str) #将unicode数据再按gbk编码 以便print
print'----------------------------------------------'
rawstr=u'zjh123朱金华'
print rawstr,repr(rawstr),type(rawstr) #直接就是unicode编码
str=rawstr.encode('utf-8')
print str,repr(str),type(str) #按照utf-8编码, 不用先解码了, 解码就出错了
str=rawstr.encode('gbk')
print str,repr(str),type(str) #可以打印
将源文件编码为ANSI格式后, 实际就是windows所谓内码, 目前测试环境是GBK了
rawstr='zjh123朱金华'
print rawstr,repr(rawstr),type(rawstr) #原编码后'zjh123\xd6\xec\xbd\xf0\xbb\xaa' 与上面的gbk编码是一样的
str=rawstr.decode('gbk').encode('utf-8') #编码为utf-8 'zjh123\xe6\x9c\xb1\xe9\x87\x91\xe5\x8d\x8e'
print str,repr(str),type(str)
str=rawstr.decode('gb2312').encode('gbk') #'zjh123\xd6\xec\xbd\xf0\xbb\xaa' gbk是gb2312的扩展, 当然编码还是一样的了
print str,repr(str),type(str)
'''输出为:
zjh123朱金华 'zjh123\xd6\xec\xbd\xf0\xbb\xaa' <type 'str'>
zjh123鏈遍噾鍗?'zjh123\xe6\x9c\xb1\xe9\x87\x91\xe5\x8d\x8e' <type 'str'>
zjh123朱金华 'zjh123\xd6\xec\xbd\xf0\xbb\xaa' <type 'str'>
'''