Python中使用中文的方法
更新時(shí)間:2011年02月19日 17:21:11 作者:
python的中文問(wèn)題一直是困擾新手的頭疼問(wèn)題,這篇文章將給你詳細(xì)地講解一下這方面的知識(shí)。當(dāng)然,幾乎可以確定的是,在將來(lái)的版本中,python會(huì)徹底解決此問(wèn)題,不用我們這么麻煩了。
先來(lái)看看python的版本:
>>> import sys
>>> sys.version
'2.5.1 (r251:54863, Apr 18 2007, 08:51:08) [MSC v.1310 32 bit (Intel)]'
(一)
用記事本創(chuàng)建一個(gè)文件ChineseTest.py,默認(rèn)ANSI:
s = "中文"
print s
測(cè)試一下瞧瞧:
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.python.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.python.org/peps/pep-0263.html for details
無(wú)濟(jì)于事。。。
既然它提供了網(wǎng)址,那就看看吧。簡(jiǎn)單地瀏覽一下,終于知道如果文件里有非ASCII字符,需要在第一行或第二行指定編碼聲明。把ChineseTest.py文件的編碼重新改為ANSI,并加上編碼聲明:
# coding=gbk
s = "中文"
print s
再試一下:
E:\Project\Python\Test>python ChineseTest.py
中文
正??海?
(二)
看一看它的長(zhǎng)度:
# coding=gbk
s = "中文"
print len(s)
結(jié)果:4。
s這里是str類型,所以計(jì)算的時(shí)候一個(gè)中文相當(dāng)于兩個(gè)英文字符,因此長(zhǎng)度為4。
我們這樣寫:
# coding=gbk
s = "中文"
s1 = u"中文"
s2 = unicode(s, "gbk") #省略參數(shù)將用python默認(rèn)的ASCII來(lái)解碼
s3 = s.decode("gbk") #把str轉(zhuǎn)換成unicode是decode,unicode函數(shù)作用與之相同
print len(s1)
print len(s2)
print len(s3)
結(jié)果:
2
2
2
(三)
接著來(lái)看看文件的處理:
建立一個(gè)文件test.txt,文件格式用ANSI,內(nèi)容為:
abc中文
用python來(lái)讀取
# 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來(lái)編輯的,但當(dāng)我用Windows自帶的記事本編輯并存成UTF-8格式時(shí),
運(yùn)行時(shí)報(bào)錯(cuò):
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
原來(lái),某些軟件,如notepad,在保存一個(gè)以UTF-8編碼的文件時(shí),會(huì)在文件開始的地方插入三個(gè)不可見的字符(0xEF 0xBB 0xBF,即BOM)。
因此我們?cè)谧x取時(shí)需要自己去掉這些字符,python中的codecs module定義了這個(gè)常量:
# 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中文
(四)一點(diǎn)遺留問(wèn)題
在第二部分中,我們用unicode函數(shù)和decode方法把str轉(zhuǎn)換成unicode。為什么這兩個(gè)函數(shù)的參數(shù)用"gbk"呢?
第一反應(yīng)是我們的編碼聲明里用了gbk(# coding=gbk),但真是這樣?
修改一下源文件:
# coding=utf-8
s = "中文"
print unicode(s, "utf-8")
運(yùn)行,報(bào)錯(cuò):
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
顯然,如果前面正常是因?yàn)閮蛇叾际褂昧薵bk,那么這里我保持了兩邊utf-8一致,也應(yīng)該正常,不至于報(bào)錯(cuò)。
更進(jìn)一步的例子,如果我們這里轉(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.
簡(jiǎn)單地說(shuō),python中的print直接把字符串傳遞給操作系統(tǒng),所以你需要把str解碼成與操作系統(tǒng)一致的格式。Windows使用CP936(幾乎與gbk相同),所以這里可以使用gbk。
最后測(cè)試:
# coding=utf-8
s = "中文"
print unicode(s, "cp936")
結(jié)果:中文
>>> import sys
>>> sys.version
'2.5.1 (r251:54863, Apr 18 2007, 08:51:08) [MSC v.1310 32 bit (Intel)]'
(一)
用記事本創(chuàng)建一個(gè)文件ChineseTest.py,默認(rèn)ANSI:
s = "中文"
print s
測(cè)試一下瞧瞧:
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.python.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.python.org/peps/pep-0263.html for details
無(wú)濟(jì)于事。。。
既然它提供了網(wǎng)址,那就看看吧。簡(jiǎn)單地瀏覽一下,終于知道如果文件里有非ASCII字符,需要在第一行或第二行指定編碼聲明。把ChineseTest.py文件的編碼重新改為ANSI,并加上編碼聲明:
# coding=gbk
s = "中文"
print s
再試一下:
E:\Project\Python\Test>python ChineseTest.py
中文
正??海?
(二)
看一看它的長(zhǎng)度:
# coding=gbk
s = "中文"
print len(s)
結(jié)果:4。
s這里是str類型,所以計(jì)算的時(shí)候一個(gè)中文相當(dāng)于兩個(gè)英文字符,因此長(zhǎng)度為4。
我們這樣寫:
# coding=gbk
s = "中文"
s1 = u"中文"
s2 = unicode(s, "gbk") #省略參數(shù)將用python默認(rèn)的ASCII來(lái)解碼
s3 = s.decode("gbk") #把str轉(zhuǎn)換成unicode是decode,unicode函數(shù)作用與之相同
print len(s1)
print len(s2)
print len(s3)
結(jié)果:
2
2
2
(三)
接著來(lái)看看文件的處理:
建立一個(gè)文件test.txt,文件格式用ANSI,內(nèi)容為:
abc中文
用python來(lái)讀取
# 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來(lái)編輯的,但當(dāng)我用Windows自帶的記事本編輯并存成UTF-8格式時(shí),
運(yùn)行時(shí)報(bào)錯(cuò):
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
原來(lái),某些軟件,如notepad,在保存一個(gè)以UTF-8編碼的文件時(shí),會(huì)在文件開始的地方插入三個(gè)不可見的字符(0xEF 0xBB 0xBF,即BOM)。
因此我們?cè)谧x取時(shí)需要自己去掉這些字符,python中的codecs module定義了這個(gè)常量:
# 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中文
(四)一點(diǎn)遺留問(wèn)題
在第二部分中,我們用unicode函數(shù)和decode方法把str轉(zhuǎn)換成unicode。為什么這兩個(gè)函數(shù)的參數(shù)用"gbk"呢?
第一反應(yīng)是我們的編碼聲明里用了gbk(# coding=gbk),但真是這樣?
修改一下源文件:
# coding=utf-8
s = "中文"
print unicode(s, "utf-8")
運(yùn)行,報(bào)錯(cuò):
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
顯然,如果前面正常是因?yàn)閮蛇叾际褂昧薵bk,那么這里我保持了兩邊utf-8一致,也應(yīng)該正常,不至于報(bào)錯(cuò)。
更進(jìn)一步的例子,如果我們這里轉(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.
簡(jiǎn)單地說(shuō),python中的print直接把字符串傳遞給操作系統(tǒng),所以你需要把str解碼成與操作系統(tǒng)一致的格式。Windows使用CP936(幾乎與gbk相同),所以這里可以使用gbk。
最后測(cè)試:
# coding=utf-8
s = "中文"
print unicode(s, "cp936")
結(jié)果:中文
相關(guān)文章
Python實(shí)現(xiàn)的科學(xué)計(jì)算器功能示例
這篇文章主要介紹了Python實(shí)現(xiàn)的科學(xué)計(jì)算器功能,涉及Python基于數(shù)值運(yùn)算與事件響應(yīng)實(shí)現(xiàn)科學(xué)計(jì)算器功能相關(guān)操作技巧,需要的朋友可以參考下2017-08-08用Python實(shí)現(xiàn)簡(jiǎn)單的人臉識(shí)別功能步驟詳解
這篇文章主要介紹了用Python實(shí)現(xiàn)簡(jiǎn)單的人臉識(shí)別功能步驟詳解,本文給大家介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或工作具有一定的參考借鑒價(jià)值,需要的朋友可以參考下2021-03-03TensorFlow神經(jīng)網(wǎng)絡(luò)構(gòu)造線性回歸模型示例教程
這篇文章主要為大家介紹了TensorFlow構(gòu)造線性回歸模型示例教程,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步2021-11-11python線程安全及多進(jìn)程多線程實(shí)現(xiàn)方法詳解
這篇文章主要介紹了python線程安全及多進(jìn)程多線程實(shí)現(xiàn)方法詳解,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友可以參考下2019-09-09Python裝飾器的應(yīng)用場(chǎng)景代碼總結(jié)
這篇文章主要介紹了Python裝飾器的應(yīng)用場(chǎng)景,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友可以參考下2020-04-04