(一) 用记事本创建一个文件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
原来,某些软件,如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: '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.