Python中使用中文的方法
2020-02-23 04:46:04
供稿:網友
先來看看python的版本:
>>> import sys
>>> sys.version
'2.5.1 (r251:54863, Apr 18 2007, 08:51:08) [MSC v.1310 32 bit (Intel)]'
(一)
用記事本創建一個文件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.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
無濟于事。。。
既然它提供了網址,那就看看吧。簡單地瀏覽一下,終于知道如果文件里有非ASCII字符,需要在第一行或第二行指定編碼聲明。把ChineseTest.py文件的編碼重新改為ANSI,并加上編碼聲明:
# coding=gbk
s = "中文"
print s
再試一下:
E:/Project/Python/Test>python ChineseTest.py
中文
正??海?
(二)
看一看它的長度:
# coding=gbk
s = "中文"
print len(s)
結果:4。
s這里是str類型,所以計算的時候一個中文相當于兩個英文字符,因此長度為4。
我們這樣寫:
# coding=gbk
s = "中文"
s1 = u"中文"
s2 = unicode(s, "gbk") #省略參數將用python默認的ASCII來解碼
s3 = s.decode("gbk") #把str轉換成unicode是decode,unicode函數作用與之相同
print len(s1)
print len(s2)
print len(s3)
結果:
2
2
2
(三)
接著來看看文件的處理:
建立一個文件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()