python中文亂碼問題大總結

fmwg 9年前發布 | 83K 次閱讀 Python開發 Python

在運行這樣類似的代碼:

#!/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編碼的字符串的結果。

下面代碼可能比較通用一些,如下:

#!/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')


看看下面一段代碼:

#!/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



import sys   
reload(sys)   
sys.setdefaultencoding('utf-8')   #修改默認編碼方式,默認為ascci  
print sys.getdefaultencoding() 

content = getPageContent("http://www.xxx.com/") 
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


import sys 
reload(sys) 
sys.setdefaultencoding('utf-8')   #修改默認編碼方式,默認為ascci
print sys.getdefaultencoding()
content = getPageContent("http://www.xxx.com/")
print content.decode('utf-8').encode('gb2312')


上面的代碼的意思:向www.xxx.com網站請求他的主頁,(如果直接是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對象。


 本文由用戶 fmwg 自行上傳分享,僅供網友學習交流。所有權歸原作者,若您的權利被侵害,請聯系管理員。
 轉載本站原創文章,請注明出處,并保留原始鏈接、圖片水印。
 本站是一個以用戶分享為主的開源技術平臺,歡迎各類分享!