Python中文处理zhoo.xuan@gmail.com2011.3.5先看个熟悉的异常:原因:ascii编码无法处理超过128的值也就是超过27ASCII编码:使用了7位来表示字符,所能表示的字符数量也就是0~127对于中文来说,远远不够于是。。。讲点ascii历史Unicode顺应而生!Unicodeisacomputingindustrystandardfortheconsistentencoding,representationandhandlingoftextexpressedinmostoftheworld'swritingsystems.--摘自wikipedia刚才那个太抽象哈unicode是个方便各种编码之间转换的标准,它可以包含世界上的所有字符codepoint,unicode标准定义了如何通过codepoint来表示字符。codepoint是个int型的值,用16位表示。形如U+897f,对应0x897f一个codepoint,也就相当与一个unicodecharacterunicodestring,也就是许多的codepoint连接在一起encode:把unicodestring转换为一系列的字节decode:把一系列的字节值转换为unicodestringgbk编码:使用了两个字节来表示一个字符utf-8编码:1,codepointis<128,ascii2,1280x7ff,返回三个字节.python中的内建类型:unicodereturnunicodestringimportsyssys.getdefaultencoding()可以看到每个unicode实例的默认编码为utf-8u=unicode('西')utf8=u.encode('utf-8')gbk=u.encode('gbk')gbk.decode('gbk').encode('utf8')理论就Over拉,说说我在使用中遇到的问题;)1,解释器ipythonu1=u'西'u2=unicode('西')ipython对u1的处理是有问题的,返回的是经过encode后的值,显示有问题问题描述:https://github.com/ipython/ipython/issuesearch?state=open&q=encodings#issue/25临时解决办法:使用hackipy2.py来启动ipython,目前2,打开文件时roamin9Bot中记录日志的方法deflog(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()python打开文件默认使用的编码为ascii在python源码中,我们可以通过在文件的开头两行使用模式:coding[:=]\s*([-\w.]+)只要与上述的正则匹配,就可以声明此文件的编码打开普通文件时,两种打开方式open('/path/to/file','mode')codecs.open('/path/to/file','mode',encoding='utf-8')3,\u4e00-\u9fa5要注意pattern的编码是否和string的编码一致4,web.pyEndQ&A感谢你们的耐心;)@roamin9zhoo.xuan@gmail.com