蔷薇525 发表于 2017-4-23 08:08:50

Python 中文乱码

  开始接触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')
页: [1]
查看完整版本: Python 中文乱码