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 no encoding declared; 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 no encoding declared; 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格式时,

运行时报错:

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")

结果:中文

转载于:https://blog.51cto.com/7492110/1586560

Python、Unicode和中文相关推荐

  1. Unicode(UTF-8, UTF-16)令人混淆的概念 和 python unicode转中文及转换默认编码

    Unicode(UTF-8, UTF-16)令人混淆的概念 [转载](https://www.cnblogs.com/fnlingnzb-learner/p/6163205.html) 为啥需要Uni ...

  2. Python Unicode与中文处理

    http://my.oschina.net/u/201886/blog/64692 From: http://hi.baidu.com/jackleehit/blog/item/ea93618e105 ...

  3. python unicode转中文_Python将Unicode代码转换为中文字符的几种方法,python,unicode,编码,汉字...

    Python中有两种默认的字符串:str和unicode.在Python中一定要注意区分"Unicode字符串" 和"unicode对象"的区别.后面所有的&q ...

  4. python unicode转中文_python3中Unicode字符转中文

    python3中将Unicode字符串转成中文 用python爬虫爬取数据时,有时候会发现爬取的数据类似于 "\u3010\u6f14\u5531\u4f1a\u30112000-\u62c ...

  5. python unicode编码转换中文_python unicode转中文及转换默认编码

    一. 在爬虫抓取网页信息时常需要将类似"\u4eba\u751f\u82e6\u77ed\uff0cpy\u662f\u5cb8"转换为中文,实际上这是unicode的中文编码.可 ...

  6. python utf-8编码转换中文_python实现unicode转中文及转换默认编码的方法

    本文实例讲述了python实现unicode转中文及转换默认编码的方法.分享给大家供大家参考,具体如下: 一.在爬虫抓取网页信息时常需要将类似"\u4eba\u751f\u82e6\u77e ...

  7. python文件编码转换工具_python实现unicode转中文及转换默认编码的方法

    本文实例讲述了python实现unicode转中文及转换默认编码的方法.分享给大家供大家参考,具体如下: 一.在爬虫抓取网页信息时常需要将类似"\u4eba\u751f\u82e6\u77e ...

  8. python unicode码转换_python实现unicode转中文及转换默认编码的方法

    本文实例讲述了python实现unicode转中文及转换默认编码的方法.分享给大家供大家参考,具体如下: 一.在爬虫抓取网页信息时常需要将类似"\u4eba\u751f\u82e6\u77e ...

  9. python unicode编码转换中文_python实现unicode转中文及转换默认编码的方法

    本文实例讲述了python实现unicode转中文及转换默认编码的方法.分享给大家供大家参考,具体如下: 一.在爬虫抓取网页信息时常需要将类似"\u4eba\u751f\u82e6\u77e ...

最新文章

  1. windows核心编程学习笔记(六)动态链接库
  2. hadoop2.0集群进程_hadoop集群基本进程
  3. 6174C语言编程,C语言验证6174数学问题
  4. eclipse 达梦 连接_达梦Hibernate Spring集成开发示例
  5. 【渝粤题库】国家开放大学2021春1332中文学科论文写作题目
  6. 手写实现java中的trim_JS中字符串trim()使用示例
  7. redis session java获取attribute_面试题:给我说说你能想到几种分布式session实现?...
  8. Frameset导致Cookies和Session丢失的原因及解决办法
  9. hive 2.1.1 mysql_Hive2.1.1集群搭建
  10. 输入一个正整数数组,把数组里所有数字拼接起来排成一个数,打印能拼接出的所有数字中最小的一个。例如输入数组{3,32,321},则打印出这三个数字能排成的最小数字为321323。
  11. TakeColor鼠标位置不对/取色不准
  12. Python:批量转换图片格式
  13. 社交网络分析算法应用,社交网络分析算法
  14. arcgis公里坐标转经纬度_利用arcgis实现经纬度和平面坐标互转
  15. codesys工控机_CoDeSys
  16. P68是什么意思 IP67和IP68等级有什么区别
  17. JavaScript基础知识和jQuery基础知识简介
  18. Centos7设置阿里源
  19. 【C语言面试复试汇总】
  20. 13.“二四六分明”与特定变格

热门文章

  1. SLAM精度测评——EVO
  2. ASP.net实现无扩展名的URL重写。简单、方便、无需ISAPI
  3. 【AI】吴恩达斯坦福机器学习中文笔记汇总
  4. 【Qt】QImage加载bmp位图数据
  5. python中属性和类级变量_六、Python类变量和实例变量(类属性和实例属性)
  6. mysql网页后台_jsp+servlet+mysql开发java web旅游网站,有后台管理系统
  7. linux进程下的线程数,Linux下查看进程线程数的方法
  8. java中注解的使用_java中注解的使用
  9. 4块硬盘做raid几_HP-P4500存储RAID硬盘离线数据恢复案例
  10. 【Java】阿里巴巴java开发手册总结(我能看懂的)