python中文乱码问题大总结

        在运行这样类似的代码:

1
2
3
#!/usr/bin/env python
s = "中文"
print  s

 

最近经常遇到这样的问题:

问题一:SyntaxError: Non-ASCII character '\xe4' in file E:\coding\python\Untitled 6.py on line 3, but no encoding declared; see http://www.python.org/peps/pep-0263.html for details

问题二:UnicodeDecodeError: 'ascii' codec can't decode byte 0xe5 in position 108: ordinal not in range(128)

问题三:UnicodeEncodeError: 'gb2312' codec can't encode character u'\u2014' in position 72366: illegal multibyte sequence

这些都是跟字符编码有关的问题,很郁闷,中文总是弄不出来,找了很多方案,这里有些是我前几天找到的一些方案,拿出来给大家分享一下哈

  字符串在Python内部的表示是unicode 编码,因此,在做编码转换时,通常需要以unicode作为中间编码,即先将其他编码的字符串解码(decode)成unicode,再从unicode编码(encode)成另一种编码。

decode的作用是将其他编码的字符串转换成unicode编码,如str1.decode('gb2312'),表示将gb2312编码的字符串str1转换成unicode编码。

encode的作用是将unicode编码转换成其他编码的字符串,如str2.encode('gb2312'),表示将unicode编码的字符串str2转换成gb2312编码。

在某些IDE中,字符串的输出总是出现乱码,甚至错误,其实是由于IDE的结果输出控制台自身不能显示字符串的编码,而不是程序本身的问题。

如在UliPad中运行如下代码:

s=u"中文"

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编码的字符串的结果。

下面代码可能比较通用一些,如下:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
#!/usr/bin/env python  
#coding=utf-8  
s = "中文"
if  isinstance (s,  unicode ): 
     #s=u"中文"  
     print  s.encode( 'gb2312'
else
     #s="中文"  
     print  s.decode( 'utf-8' ).encode( 'gb2312' )
#!/usr/bin/env python
#coding=utf-8
s = "中文"
if  isinstance (s,  unicode ):
  #s=u"中文"
  print  s.encode( 'gb2312' )
else :
  #s="中文"
  print  s.decode( 'utf-8' ).encode( 'gb2312' )

 

看看下面一段代码:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
#!/usr/bin/env python  
#coding=utf-8  
#python version:2.7.4 
#system:windows xp 
   
import  httplib2
def  getPageContent(url):
     '''''
     使用httplib2用编程的方式根据url获取网页内容
     将bytes形式的内容转换成utf-8的字符串
     '''
     #使用ie9的user-agent,如果不设置user-agent将会得到403禁止访问 
     headers = { 'user-agent' : 'Mozilla/5.0 (compatible; MSIE 9.0; Windows NT 6.1; Trident/5.0)' ,
             'cache-control' : 'no-cache' }
     if  url:
          response,content  =  httplib2.Http().request(url,headers = headers)
            
          if  response.status  = =  200  :
             return  content

 

 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
import  sys  
reload (sys)  
sys.setdefaultencoding( 'utf-8' )    #修改默认编码方式,默认为ascci 
print  sys.getdefaultencoding()
   
content  =  getPageContent( "http://www.oschina.net/" )
print  content.decode( 'utf-8' ).encode( 'gb2312' )
#!/usr/bin/env python
#coding=utf-8
#python version:2.7.4
#system:windows xp
import  httplib2
def  getPageContent(url):
     '''
     使用httplib2用编程的方式根据url获取网页内容
     将bytes形式的内容转换成utf-8的字符串
     '''
     #使用ie9的user-agent,如果不设置user-agent将会得到403禁止访问
     headers = { 'user-agent' : 'Mozilla/5.0 (compatible; MSIE 9.0; Windows NT 6.1; Trident/5.0)' ,
             'cache-control' : 'no-cache' }
     if  url:
          response,content  =  httplib2.Http().request(url,headers = headers)
          
          if  response.status  = =  200  :
             return  content

 

1
2
3
4
5
6
import  sys
reload (sys)
sys.setdefaultencoding( 'utf-8' )    #修改默认编码方式,默认为ascci
print  sys.getdefaultencoding()
content  =  getPageContent( "http://www.oschina.net/" )
print  content.decode( 'utf-8' ).encode( 'gb2312' )

 

上面的代码的意思:向www.oschina.net网站请求他的主页,(如果直接是utf-8编码,不能输出中文)想将编码方式为utf-8转向gd2312,出现问题三

当我把它将print content.decode('utf-8').encode('gb2312')改成  print content.decode('utf-8').encode('gb2312', ‘ignore’)时,OK了,可以显示中文了,但不敢确定是否为全部,貌似只有部分吧,有些不能用gb2312编码

然而,当我把网站换成 www.soso.com时,不用转为gb2312,用utf-8即可正常显示中文

总结一下:

  向文件直接输出ss会抛出同样的异常。在处理unicode中文字符串的时候,必须首先对它调用encode函数,转换成其它编码输出。这一点对各个环境都一样。在Python中,“str”对象就是一个字节数组,至于里面的内容是不是一个合法的字符串,以及这个字符串采用什么编码(gbk, utf-8, unicode)都不重要。这些内容需要用户自己记录和判断。这些的限制也同样适用于“unicode”对象。要记住“unicode”对象中的内容可绝对不一定就是合法的unicode字符串,我们很快就会看到这种情况。在windows的控制台上,支持gbk编码的str对象和unicode编码的unicode对象。

猜你喜欢

转载自hugoren.iteye.com/blog/2301619