1.unicode、gbk、gb2312、utf-8的關系
http://www.pythonclub.org/python-basic/encode-detail 這篇文章寫的比較好,utf-8是unicode的一種實現方式,unicode、gbk、gb2312是編碼字符集;
2.python中的中文編碼問題
2.1 .py文件中的編碼
Python 默認腳本文件都是 ANSCII 編碼的,當文件 中有非 ANSCII 編碼范圍內的字符的時候就要使用"編碼指示"來修正。 一個module的定義中,如果.py文件中包含中文字符(嚴格的說是含有非anscii字符),則需要在第一行或第二行指定編碼聲明:
# -*- coding=utf-8 -*-或者 #coding=utf-8 其他的編碼如:gbk、gb2312也可以; 否則會出現類似:SyntaxError: Non-ASCII character '/xe4' in file ChineseTest.py on line 1, but no encoding declared; see http://www.pytho for details這樣的異常信息;n.org/peps/pep-0263.html
2.2 python中的編碼與解碼
先說一下python中的字符串類型,在python中有兩種字符串類型,分別是str和unicode,他們都是basestring的派生類;str類型是一個包含Characters represent (at least) 8-bit bytes的序列;unicode的每個unit是一個unicode obj;所以:
len(u'中國')的值是2;len('ab')的值也是2;
在str的文檔中有這樣的一句話:The string data type is also used to represent arrays of bytes, e.g., to hold data read from a file. 也就是說在讀取一個文件的內容,或者從網絡上讀取到內容時,保持的對象為str類型;如果想把一個str轉換成特定編碼類型,需要把str轉為Unicode,然后從unicode轉為特定的編碼類型如:utf-8、gb2312等;
python中提供的轉換函數:
unicode轉為 gb2312,utf-8等
# -*- coding=UTF-8 -*-
if __name__ == '__main__':
s = u'中國'
s_gb = s.encode('gb2312')
utf-8,GBK轉換為unicode 使用函數unicode(s,encoding) 或者s.decode(encoding)
# -*- coding=UTF-8 -*-
if __name__ == '__main__':
s = u'中國'
#s為unicode先轉為utf-8
s_utf8 = s.encode('UTF-8')
assert(s_utf8.decode('utf-8') == s)
普通的str轉為unicode
# -*- coding=UTF-8 -*-
if __name__ == '__main__':
s = '中國'
su = u'中國''
#s為unicode先轉為utf-8
#因為s為所在的.py(# -*- coding=UTF-8 -*-)編碼為utf-8
s_unicode = s.decode('UTF-8')
assert(s_unicode == su)
#s轉為gb2312,先轉為unicode再轉為gb2312
s.decode('utf-8').encode('gb2312')
#如果直接執行s.encode('gb2312')會發生什么?
s.encode('gb2312')
# -*- coding=UTF-8 -*-
if __name__ == '__main__':
s = '中國'
#如果直接執行s.encode('gb2312')會發生什么?
s.encode('gb2312')
這里會發生一個異常:
Python 會自動的先將 s 解碼為 unicode ,然后再編碼成 gb2312。因為解碼是python自動進行的,我們沒有指明解碼方式,python 就會使用 sys.defaultencoding 指明的方式來解碼。很多情況下 sys.defaultencoding 是 ANSCII,如果 s 不是這個類型就會出錯。
拿上面的情況來說,我的 sys.defaultencoding 是 anscii,而 s 的編碼方式和文件的編碼方式一致,是 utf8 的,所以出錯了: UnicodeDecodeError: 'ascii' codec can't decode byte 0xe4 in position 0: ordinal not in range(128)
對於這種情況,我們有兩種方法來改正錯誤:
一是明確的指示出 s 的編碼方式
#! /usr/bin/env python
# -*- coding: utf-8 -*-
s = '中文'
s.decode('utf-8').encode('gb2312')
二是更改 sys.defaultencoding 為文件的編碼方式
#! /usr/bin/env python
# -*- coding: utf-8 -*-
import sys
reload(sys) # Python2.5 初始化后會刪除 sys.setdefaultencoding 這個方法,我們需要重新載入
sys.setdefaultencoding('utf-8')
str = '中文'
str.encode('gb2312')
文件編碼與print函數
建立一個文件test.txt,文件格式用ANSI,內容為:
abc中文
用python來讀取
# coding=gbk
print open("Test.txt").read()
結果:abc中文
把文件格式改成UTF-8:
結果:abc涓枃
顯然,這里需要解碼:
# coding=gbk
import codecs
print open("Test.txt").read().decode("utf-8")
結果:abc中文
上面的test.txt我是用Editplus來編輯的,但當我用Windows自帶的記事本編輯並存成UTF-8格式時,
運行時報錯:
Traceback (most recent call last):
File "ChineseTest.py", line 3, in <module>
print open("Test.txt").read().decode("utf-8")
UnicodeEncodeError: 'gbk' codec can't encode character u'/ufeff' in position 0: illegal multibyte sequence
原來,某些軟件,如notepad,在保存一個以UTF-8編碼的文件時,會在文件開始的地方插入三個不可見的字符(0xEF 0xBB 0xBF,即BOM)。
因此我們在讀取時需要自己去掉這些字符,python中的codecs module定義了這個常量:
# coding=gbk
import codecs
data = open("Test.txt").read()
if data[:3] == codecs.BOM_UTF8:
data = data[3:]
print data.decode("utf-8")
結果:abc中文
(四)一點遺留問題
在第二部分中,我們用unicode函數和decode方法把str轉換成unicode。為什么這兩個函數的參數用"gbk"呢?
第一反應是我們的編碼聲明里用了gbk(# coding=gbk),但真是這樣?
修改一下源文件:
# coding=utf-8
s = "中文"
print unicode(s, "utf-8")
運行,報錯:
Traceback (most recent call last):
File "ChineseTest.py", line 3, in <module>
s = unicode(s, "utf-8")
UnicodeDecodeError: 'utf8' codec can't decode bytes in position 0-1: invalid data
顯然,如果前面正常是因為兩邊都使用了gbk,那么這里我保持了兩邊utf-8一致,也應該正常,不至於報錯。
更進一步的例子,如果我們這里轉換仍然用gbk:
# coding=utf-8
s = "中文"
print unicode(s, "gbk")
結果:中文
python中的print原理:
When Python executes a print statement, it simply passes the output to the operating system (using fwrite() or something like it), and some other program is responsible for actually displaying that output on the screen. For example, on Windows, it might be the Windows console subsystem that displays the result. Or if you're using Windows and running Python on a Unix box somewhere else, your Windows SSH client is actually responsible for displaying the data. If you are running Python in an xterm on Unix, then xterm and your X server handle the display.
To print data reliably, you must know the encoding that this display program expects.
最后測試:
# coding=utf-8 s = "中文" print unicode(s, "cp936")
# 結果:中文
>>> s="哈哈" >>> s '\xe5\x93\x88\xe5\x93\x88' >>> print s #這里為啥就可以呢? 見上文對print的解釋 哈哈 >>> import sys >>> sys.getdefaultencoding() 'ascii' >>> print s.encode('utf8') # s在encode之前系統默認按ascii模式把s解碼為unicode,然后再encode為utf8 Traceback (most recent call last): File "<stdin>", line 1, in ? UnicodeDecodeError: 'ascii' codec can't decode byte 0xe5 in position 0: ordinal not in range(128) >>> print s.decode('utf-8').encode('utf8') 哈哈 >>>
編碼問題測試
使用 chardet 可以很方便的實現字符串/文件的編碼檢測
例子如下:
>>> import urllib >>> rawdata = urllib .urlopen ( 'http://www.google.cn/' ) .read ( ) >>> import chardet
>>> chardet.detect ( rawdata) { 'confidence' : 0.98999999999999999 , 'encoding' : 'GB2312' } >>>
chardet 下載地址 http://chardet.feedparser.org/
特別提示:
在工作中,經常遇到,讀取一個文件,或者是從網頁獲取一個問題,明明看着是gb2312的編碼,可是當使用decode轉時,總是出錯,這個時候,可以使用decode('gb18030')這個字符集來解決,如果還是有問題,這個時候,一定要注意,decode還有一個參數,比如,若要將某個String對象s從gbk內碼轉換為UTF-8,可以如下操作
s.decode('gbk').encode('utf-8′)
可是,在實際開發中,我發現,這種辦法經常會出現異常:
UnicodeDecodeError: ‘gbk' codec can't decode bytes in position 30664-30665: illegal multibyte sequence
這 是因為遇到了非法字符——尤其是在某些用C/C++編寫的程序中,全角空格往往有多種不同的實現方式,比如/xa3/xa0,或者/xa4/x57,這些 字符,看起來都是全角空格,但它們並不是“合法”的全角空格(真正的全角空格是/xa1/xa1),因此在轉碼的過程中出現了異常。
這樣的問題很讓人頭疼,因為只要字符串中出現了一個非法字符,整個字符串——有時候,就是整篇文章——就都無法轉碼。
解決辦法:
s.decode('gbk', ‘ignore').encode('utf-8′)
因為decode的函數原型是decode([encoding], [errors='strict']),可以用第二個參數控制錯誤處理的策略,默認的參數就是strict,代表遇到非法字符時拋出異常;
如果設置為ignore,則會忽略非法字符;
如果設置為replace,則會用?取代非法字符;
如果設置為xmlcharrefreplace,則使用XML的字符引用。
python文檔
decode( [encoding[, errors]])
Decodes the string using the codec registered for encoding. encoding defaults to the default string encoding. errors may be given to set a different error handling scheme. The default is 'strict', meaning that encoding errors raise UnicodeError. Other possible values are 'ignore', 'replace' and any other name registered via codecs.register_error, see section 4.8.1.
詳細出處參考:http://www.jb51.net/article/16104.htm
參考文獻
【1】http://blog.chinaunix.net/u2/68206/showart.php?id=668359
【2】http://www.pythonclub.org/python-basic/codec
【3】http://www.pythonclub.org/python-scripts/quanjiao-banjiao
【4】http://www.pythonclub.org/python-basic/chardet