首頁  >  文章  >  後端開發  >  關於Python中的中文程式設計問題

關於Python中的中文程式設計問題

零到壹度
零到壹度原創
2018-04-16 11:38:501549瀏覽

這篇文章介紹的內容是關於Python中的中文編碼問題,有著一定的參考價值,現在分享給大家,有需要的朋友可以參考一下

1.python中的中文編碼問題

1.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

1.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在 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: &#39;gbk&#39; codec can&#39;t encode character u&#39;/ufeff&#39; 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: &#39;utf8&#39; codec can&#39;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, item that output on the screen. For example, on Windows 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 in an x​​termserver in an x​​term. handle the display.

  To print data reliably, you must know the encoding that this display program expects.

简单地说,python中的print直接把字符串传递给操作系统,所以你需要把str解码成与操作系统一致的格式。Windows使用CP936(几乎与gbk相同),所以这里可以使用gbk。
最后测试:

# coding=utf-8
s = "中文"
rint unicode(s, "cp936")
# 结果:中文

这也可以解释为何如下输出不一致:

>>> s="哈哈"
>>> s&#39;
\xe5\x93\x88\xe5\x93\x88&#39;
>>> print s  #这里为啥就可以呢? 见上文对print的解释
哈哈>>> import sys
>>> sys.getdefaultencoding() &#39;
ascii&#39;
>>> print s.encode(&#39;utf8&#39;)  # s在encode之前系统默认按ascii模式把s解码为unicode,然后再encode为utf8
Traceback (most recent call last):
File "<stdin>", line 1, in ?
UnicodeDecodeError: &#39;ascii&#39; codec can&#39;t decode byte 0xe5 in position 0: ordinal not in range(128)
>>> print s.decode(&#39;utf-8&#39;).encode(&#39;utf8&#39;)
哈哈
>>>

编码问题测试

使用 chardet 可以很方便的实现字符串/文件的编码检测

例子如下:

>>>
 import
 urllib>>>
 rawdata = urllib.urlopen(&#39;http://www.google.cn/&#39;).read()>>>
 import
 chardet
>>>
 chardet.detect(rawdata){&#39;confidence&#39;: 0.98999999999999999, &#39;encoding&#39;: &#39;GB2312&#39;}>>>

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(&#39;gbk&#39;, ‘ignore&#39;).encode(&#39;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】Python编码转换

【2】全角半角转换的Python实现

【3】Python编码实现

以上是關於Python中的中文程式設計問題的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述:
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn