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 no encoding declared; seehttp://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; seehttp://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格式时,
运行时报错:
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()
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.
简单地说,python中的print直接把字符串传递给操作系统,所以你需要把str解码成与操作系统一致的格式。Windows使用CP936(几乎与gbk相同),所以这里可以使用gbk。
最后测试:
# coding=utf-8
s = "中文"
print unicode(s, "cp936")
结果:中文
========================
本文转自Python邮件列表:[CPyUG:47963] python unicode 和 中文 (zz,不知道原作者了)
Python中使用中文的更多相关文章
- Python中表示中文的pattern
Python中表示中文的pattern:[\u4e00-\u9fff] 汉字unicode码表: http://jlqzs.blog.163.com/blog/static/2125298320070 ...
- python中加入中文注释报错处理
python中加入中文注释,运行报错如下 解决方法: 在py文件的第一行加入 #coding:utf-8 即可
- python中打印中文
python中打印中文 在python 2.x版本中,默认是ASCII编码方式,在有业务需要输入中文时,就会出现乱码的情况.解决这种问题的一个方式就是设置py文件的编码方式.实现方式如下: 在py文件 ...
- sae python中Mysql中文乱码的解决
一開始我用的是: db=MySQLdb.connect(db=sae.const.MYSQL_DB,user=sae.const.MYSQL_USER,passwd=sae.const.MYSQL_P ...
- Python中添加中文注释报错SyntaxError: Non-UTF-8 code starting with '\xc1'
问题:在文本编辑器中编辑Python文件时添加中文注释,运行python文件时报错.SyntaxError: Non-UTF-8 code starting with '\xc1' 解决方法:在文本开 ...
- Python中使用中文正则表达式匹配指定的中文字符串
业务场景: 从中文字句中匹配出指定的中文子字符串 .这样的情况我在工作中遇到非常多, 特梳理总结如下. 难点: 处理GBK和utf8之类的字符编码, 同时正则匹配Pattern中包含汉字,要汉字正常发 ...
- 关于Python中输出中文的一点疑问
#encoding=gb2312 import urllib import re def getHtml(url): page = urllib.urlopen(url) html = page.re ...
- Windows下Python中的中文路径和中文输出问题
这几天有个项目需要写一点类似于脚本的小程序,就用Python写了,涉及到中文路径和中文输出的问题,整理一下. 有一个问题我觉得需要先强调一下,在写Python程序的时候,一定保证编码是utf-8,然后 ...
- Python中加入中文注释
最近开发学习Pyton,当加入中文注释时,运行程序报错: File SyntaxError: Non-ASCII character , but no encoding declared; see h ...
随机推荐
- js_面向对象编程
主要内容 值类型与引用类型的特征 深拷贝与浅拷贝 对象的动态特性 构造函数的执行过程 异常处理 dom操作(略) <!DOCTYPE html> <html> <head ...
- 【转】Cannot change version of project facet Dynamic Web Module to 3.1 (Eclipse Maven唯一解决方案)
If you want to use version 3.1 you need to use the following schema: http://xmlns.jcp.org/xml/ns/jav ...
- Ajax-$.ajax()方法详解
jquery中的ajax方法参数总是记不住,这里记录一下. 1.url: 要求为String类型的参数,(默认为当前页地址)发送请求的地址. 2.type: 要求为String类型的参数,请求方式(p ...
- [Webpack 2] Hashing with Webpack for long term caching
Leveraging the browser cache is an important part of page load performance. A great way to utilize t ...
- ASP.NET性能优化之分布式Session
如果我们正在使用Session,那么构建高性能可扩展的ASP.NET网站,就必须解决分布式Session的架构,因为单服务器的SESSION处理能力会很快出现性能瓶颈,这类问题也被称之为Session ...
- 复旦大学2016--2017学年第一学期高等代数I期末考试情况分析
一.期末考试成绩班级前十名 宁盛臻(100).朱民哲(92).徐钰伦(86).范凌虎(85).沈伊南(84).何陶然(84).丁知愚(83).焦思邈(83).董瀚泽(82).钱信(81) 二.总成绩计 ...
- Python开发实战教程(8)-向网页提交获取数据
来这里找志同道合的小伙伴!↑↑↑ Python应用现在如火如荼,应用范围很广.因其效率高开发迅速的优势,快速进入编程语言排行榜前几名.本系列文章致力于可以全面系统的介绍Python语言开发知识和相关知 ...
- C语言基础知识小总结(2)
上个总结比较笼统,下面写的稍微详细点吧算是. 一.控制台屏幕打印 1.putchar(); 格式: void putchar(char c); //直接把一个字符输出到屏幕上 2.print ...
- PHP解决多进程同时读写一个…
原文地址:PHP解决多进程同时读写一个文件的问题作者:陌上花开 首先PHP是支持进程的而不支持多线程(这个先搞清楚了),如果是对于文件操作,其实你只需要给文件加锁就能解决,不需要其它操作,PHP的fl ...
- “System.Transactions.Diagnostics.DiagnosticTrace”的类型初始值设定项引发异常。
今天在项目中用log4net,App.config文件中增加了configSections节点,程序运行报错“System.Transactions.Diagnostics.DiagnosticTra ...