您的位置:首页 > 编程语言 > Python开发

python处理中文

2016-01-18 09:36 567 查看
来源:http://www.djangochina.cn/forum.php?mod=viewthread&tid=118977&extra=page%3D1

字符串在Python内部的表示是unicode编码,因此,在做编码转换时,通常需要以unicode作为中间编码,即先将其他编码的字符串解码(decode)成unicode,再从unicode编码(encode)成另一种编码。

decode的作用是将其他编码的字符串转换成unicode编码,如str1.decode('gb2312'),表示将gb2312编码的字符串str1转换成unicode编码。

encode的作用是将unicode编码转换成其他编码的字符串,如str2.encode('gb2312'),表示将unicode编码的字符串str2转换成gb2312编码。

代码中字符串的默认编码与代码文件本身的编码一致。

如:s='中文'

如果是在utf8的文件中,该字符串就是utf8编码,如果是在gb2312的文件中,则其编码为gb2312。这种情况下,要进行编码转换,都需要先用decode方法将其转换成unicode编码,再使用encode方法将其转换成其他编码。

如果字符串是这样定义:s=u'中文'

则该字符串的编码就被指定为unicode了,即python的内部编码,而与代码文件本身的编码无关。因此,对于这种情况做编码转换,只需要直接使用encode方法将其转换成指定编码即可。

以日期为例:

#raw_date is a gbk-coding string

def parse_date(raw_date):

entry_date = raw_date.decode("gbk")

month = int(entry_date[0])

#unicode 对中文的长度是1,如果6月2日那么长度就是4,如果6月25日,长度就是5

if len(entry_date) == 5:

day = 10 * int(entry_date[2]) + int(entry_date[3])

else:

day = int(entry_date[2])

return 2013, month, day

复制代码

python, 中文
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: