python处理中文

来源: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方法将其转换成指定编码即可。

以日期为例:

  1. #raw_date is a gbk-coding string
  2. def parse_date(raw_date):
  3.     entry_date = raw_date.decode("gbk")
  4.     month = int(entry_date[0])
  5. #unicode 对中文的长度是1,如果6月2日那么长度就是4,如果6月25日,长度就是5
  6.     if len(entry_date) == 5:
  7.         day = 10 * int(entry_date[2]) + int(entry_date[3])
  8.     else:
  9.         day = int(entry_date[2])
  10.     return 2013, month, day
复制代码
原文地址:https://www.cnblogs.com/stevenzeng/p/5138361.html