亚洲av成人无遮挡网站在线观看,少妇性bbb搡bbb爽爽爽,亚洲av日韩精品久久久久久,兔费看少妇性l交大片免费,无码少妇一区二区三区

  免費注冊 查看新帖 |

Chinaunix

  平臺 論壇 博客 文庫
最近訪問板塊 發(fā)新帖
查看: 3880 | 回復: 0
打印 上一主題 下一主題

Python中使用中文 [復制鏈接]

論壇徽章:
0
跳轉(zhuǎn)到指定樓層
1 [收藏(0)] [報告]
發(fā)表于 2009-11-04 09:13 |只看該作者 |倒序瀏覽

                                                        Python中使用中文原文地址:http://blog.csdn.net/kernelspirit/archive/2008/07/14/2650696.aspx
                                       
[url=javascript:d=document;t=d.selection?(d.selection.type!='None'?d.selection.createRange().text:''):(d.getSelection?d.getSelection():'');void(saveit=window.open('http://wz.csdn.net/storeit.aspx?t='+escape(d.title)+'&u='+escape(d.location.href)+'&c='+escape(t),'saveit','scrollbars=no,width=590,height=300,left=75,top=20,status=no,resizable=yes'));saveit.focus();]
[/url]
                                       
                                       
                               
                               
                                       
                                       
                                       
python的中文問題一直是困擾新手的頭疼問題,這篇文章將給你詳細地講解一下這方面的知識。當然,幾乎可以確定的是,在將來的版本中,python會徹底解決此問題,不用我們這么麻煩了。
先來看看python的版本:
>>> import sys
>>> sys.version
'2.5.1 (r251:54863, Apr 18 2007, 08:51:08) [MSC v.1310 32 bit (Intel)]'
(一)
用記事本創(chuàng)建一個文件ChineseTest.py,默認ANSI:
s = "中文"
print s
測試一下瞧瞧:
E:\Project\Python\Test>python ChineseTest.py
  File "ChineseTest.py", line 1
SyntaxError: Non-ASCII character '\xd6' in file ChineseTest.py on line 1, but no encoding declared; see
http://www.pytho
n.org/peps/pep-0263.html
for details
偷偷地把文件編碼改成UTF-8:
E:\Project\Python\Test>python ChineseTest.py
  File "ChineseTest.py", line 1
SyntaxError: Non-ASCII character '\xe4' in file ChineseTest.py on line 1, but no encoding declared; see
http://www.pytho
n.org/peps/pep-0263.html
for details
無濟于事。。。
既然它提供了網(wǎng)址,那就看看吧。簡單地瀏覽一下,終于知道如果文件里有非ASCII字符,需要在第一行或第二行指定編碼聲明。把ChineseTest.py文件的編碼重新改為ANSI,并加上編碼聲明:
# coding=gbk
s = "中文"
print s
再試一下:
E:\Project\Python\Test>python ChineseTest.py
中文
正?海
(二)
看一看它的長度:
# coding=gbk
s = "中文"
print len(s)
結(jié)果:4。
s這里是str類型,所以計算的時候一個中文相當于兩個英文字符,因此長度為4。
我們這樣寫:
# coding=gbk
s = "中文"
s1 = u"中文"
s2 = unicode(s, "gbk") #省略參數(shù)將用python默認的ASCII來解碼
s3 = s.decode("gbk") #把str轉(zhuǎn)換成unicode是decode,unicode函數(shù)作用與之相同
print len(s1)
print len(s2)
print len(s3)
結(jié)果:
2
2
2
(三)
接著來看看文件的處理:
建立一個文件test.txt,文件格式用ANSI,內(nèi)容為:
abc中文
用python來讀取
# coding=gbk
print open("Test.txt").read()
結(jié)果:abc中文
把文件格式改成UTF-8:
結(jié)果:abc涓?枃
顯然,這里需要解碼:
# coding=gbk
import codecs
print open("Test.txt").read().decode("utf-8")
結(jié)果:abc中文
上面的test.txt我是用Editplus來編輯的,但當我用Windows自帶的記事本編輯并存成UTF-8格式時,
運行時報錯:
Traceback (most recent call last):
  File "ChineseTest.py", line 3, in
    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")
結(jié)果:abc中文
(四)一點遺留問題
在第二部分中,我們用unicode函數(shù)和decode方法把str轉(zhuǎn)換成unicode。為什么這兩個函數(shù)的參數(shù)用"gbk"呢?
第一反應是我們的編碼聲明里用了gbk(# coding=gbk),但真是這樣?
修改一下源文件:
# coding=utf-8
s = "中文"
print unicode(s, "utf-8")
運行,報錯:
Traceback (most recent call last):
  File "ChineseTest.py", line 3, in
    s = unicode(s, "utf-8")
UnicodeDecodeError: 'utf8' codec can't decode bytes in position 0-1: invalid data
顯然,如果前面正常是因為兩邊都使用了gbk,那么這里我保持了兩邊utf-8一致,也應該正常,不至于報錯。
更進一步的例子,如果我們這里轉(zhuǎn)換仍然用gbk:
# coding=utf-8
s = "中文"
print unicode(s, "gbk")
結(jié)果:中文
翻閱了一篇英文資料,它大致講解了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.
簡單地說,python中的print直接把字符串傳遞給操作系統(tǒng),所以你需要把str解碼成與操作系統(tǒng)一致的格式。Windows使用CP936(幾乎與gbk相同),所以這里可以使用gbk。
最后測試:
# coding=utf-8
s = "中文"
print unicode(s, "cp936")
結(jié)果:中文
========================
               
               
               
               
               

本文來自ChinaUnix博客,如果查看原文請點:http://blog.chinaunix.net/u/21908/showart_2085826.html
您需要登錄后才可以回帖 登錄 | 注冊

本版積分規(guī)則 發(fā)表回復

  

北京盛拓優(yōu)訊信息技術有限公司. 版權所有 京ICP備16024965號-6 北京市公安局海淀分局網(wǎng)監(jiān)中心備案編號:11010802020122 niuxiaotong@pcpop.com 17352615567
未成年舉報專區(qū)
中國互聯(lián)網(wǎng)協(xié)會會員  聯(lián)系我們:huangweiwei@itpub.net
感謝所有關心和支持過ChinaUnix的朋友們 轉(zhuǎn)載本站內(nèi)容請注明原作者名及出處

清除 Cookies - ChinaUnix - Archiver - WAP - TOP