SyntaxError: Non-ASCII character Python中文處理__Python

來源:互聯網
上載者:User
python的中文題目一向是困擾新手的頭疼題目,這篇文章將給你具體地講解一下這方面的常識。當然,幾乎可以斷定的是,在將來的版本中,python會徹底解決此題目,不消我們這麼麻煩了。

先來看看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 noencodingdeclared; 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 noencodingdeclared; see http://www.pytho
n.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格局時,
運行時報錯:

# coding=gbk
import codecs
print open("Test.txt").read().decode("utf-8")



本來,某些軟體,如notepad,在儲存一個以UTF-8編碼的檔案時,會在檔案開端的處所插入三個不成見的字元(0 xEF 0 xBB 0 xBF,即BOM)。
是以我們在讀取時須要本身去掉這些字元,python中的codecs module定義了這個常量:

# coding=gbk
import codecs
print open("Test.txt").read().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.

簡單地說,python中的print直接把字串傳遞給操縱體系,所以你須要把str解碼成與操縱系同一致的格局。Windows應用CP936(幾乎與gbk雷同),所以這裡可以應用gbk。
最後測試:

# coding=utf-8
s = "中文"
print unicode(s, "cp936")


成果:中文

 

原文連結:http://www.byywee.com/page/M0/S739/739904.html


聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.