您好,欢迎来到三六零分类信息网!老站,搜索引擎当天收录,欢迎发信息
免费发信息
三六零分类信息网 > 潍坊分类信息网,免费分类信息发布

Python 中文乱码

2024/5/19 0:00:46发布60次查看
开始接触python脚本,一上来就碰到了中文乱码问题。
结合网上的资料,现整理下:
字符串在python内部的表示是unicode编码,因此,在做编码转换时,通常需要以unicode作为中间编码,即先将其他编码的字符串解码(decode)成unicode,再从unicode编码(encode)成另一种编码。
decode 解码,作用是将其他编码的字符串转换成unicode编码,如str1.decode('gb2312'),表示将gb2312编码的字符串str1转换成unicode编码。 
 encode 编码,作用是将unicode编码转换成其他编码的字符串,如str2.encode('gb2312'),表示将unicode编码的字符串str2转换成gb2312编码。
如果一个字符串已经是unicode了,再进行解码则将出错,因此通常要对其编码方式是否为unicode进行判断:
isinstance(s, unicode)  #用来判断是否为unicode 
用非unicode编码形式的str来encode会报错 
 如何获得系统的默认编码? 
#!/usr/bin/python
#coding=utf-8
import sys
print sys.getdefaultencoding()  
该段程序在英文windowsxp上输出为:ascii 
在某些ide中,字符串的输出总是出现乱码,甚至错误,其实是由于ide的结果输出控制台自身不能显示字符串的编码,而不是程序本身的问题。 
如在ulipad中运行如下代码:
s=u中文  #指定为unicode编码
print s 
会提示:unicodeencodeerror: 'ascii' codec can't encode characters in position 0-1: ordinal not in range(128)。这是因为ulipad在英文windowsxp上的控制台信息输出窗口是按照ascii编码输出的(英文系统的默认编码是ascii),而上面代码中的字符串是unicode编码的,所以输出时产生了错误。
将最后一句改为:print s.encode('gb2312')
则能正确输出“中文”两个字。
若最后一句改为:print s.encode('utf8')
则输出:\xe4\xb8\xad\xe6\x96\x87,这是控制台信息输出窗口按照ascii编码输出utf8编码的字符串的结果。
unicode(str,'gb2312')与str.decode('gb2312')是一样的,都是将gb2312编码的str转为unicode编码 
使用str.__class__可以查看str的编码形式
原理说了半天,上代码:
#coding=utf-8 
#!/usr/bin/python
s=中文 
if isinstance(s, unicode): 
print s.encode('gb2312') 
else: 
print s.decode('utf-8').encode('gb2312')
潍坊分类信息网,免费分类信息发布

VIP推荐

免费发布信息,免费发布B2B信息网站平台 - 三六零分类信息网 沪ICP备09012988号-2
企业名录