python中文处理

19
Python 中中中中 [email protected] 2011.3.5

Upload: roamin9-zhou

Post on 03-Sep-2014

1.330 views

Category:

Technology


5 download

DESCRIPTION

 

TRANSCRIPT

Page 1: python中文处理

Python 中文处理[email protected]

2011.3.5

Page 2: python中文处理

先看个熟悉的异常:

原因: ascii 编码无法处理超过128 的值 也就是超过 27

Page 3: python中文处理

ASCII 编码:使用了 7 位来表示字符,所能表示的字符数量也就是0~127

对于中文来说,远远不够于是。。。

讲点 ascii 历史

Page 4: python中文处理

Unicode 顺应而生!

Unicode is a computing industry standard for the consistent encoding, representation and handling of text expressed in most of the world's writing systems. 

-- 摘自 wikipedia

Page 5: python中文处理

刚才那个太抽象哈unicode 是个方便各种编码之间转换的标准,它可以包含世界上的所有字符

code point , unicode 标准定义了如何通过 code point 来表示字符。

Page 6: python中文处理

code point 是个 int 型的值,用 16 位表示。形如 U+897f ,对应 0x897f

一个 code point ,也就相当与一个unicode character

unicode string ,也就是许多的code point 连接在一起

Page 7: python中文处理

encode: 把 unicode string 转换为一系列的字节

decode: 把一系列的字节值转换为 unicode string

Page 8: python中文处理

gbk 编码:使用了两个字节来表示一个字符utf-8 编码:     1,code point is <128, ascii     2,128< code point < 0x7ff, 返回两个字节 . 每个字节的值都在 128~255 之间 .     3,code point > 0x7ff, 返回三个字节 .

Page 9: python中文处理

python 中的内建类型: unicode

return unicode string

import sys

sys.getdefaultencoding()

可以看到每个 unicode 实例的默认编码为 utf-8

Page 10: python中文处理

u = unicode(' 西 ')

utf8 = u.encode('utf-8')

gbk = u.encode('gbk')

gbk.decode('gbk').encode('utf8')

Page 11: python中文处理

理论就 Over 拉,说说我在使用中遇到的问题 ;)

Page 12: python中文处理

1 ,解释器 ipython

u1 = u' 西 '

u2 = unicode(' 西 ')

ipython 对 u1 的处理是有问题的,返回的是经过 encode 后的值,显示有问题

Page 13: python中文处理

问题描述:https://github.com/ipython/ipython/issuesearch?state=open&q=encodings#issue/25

临时解决办法:使用 hackipy2.py 来启动ipython ,目前

Page 14: python中文处理

2 ,打开文件时roamin9Bot 中记录日志的方法 def log(self, content):        time_style = "%Y-%m-%d %H:%M:%S"        f = file('log_file', 'a')        #f = codecs.open('log_file', 'a', encoding='utf8')        f.write(content + strftime(time_style) + '\n')        f.close()

Page 15: python中文处理

python 打开文件默认使用的编码为 ascii

在 python 源码中,我们可以通过在文件的开头两行使用模式: coding[:=]\s*([-\w.]+)

只要与上述的正则匹配,就可以声明此文件的编码

Page 16: python中文处理

打开普通文件时,两种打开方式open('/path/to/file', 'mode')

codecs.open('/path/to/file', 'mode', encoding='utf-8')

Page 17: python中文处理

3 ,\u4e00-\u9fa5

要注意 pattern 的编码是否和 string 的编码一致

Page 18: python中文处理

4 , web.py

Page 19: python中文处理

End  

Q&A

感谢你们的耐心 ;)@[email protected]