• python处理中文(待补充)


    字符串在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

      

  • 相关阅读:
    mysql误删表,无备份
    感情启示录
    奸的好人之财色战场
    Word神器使用
    Maven工程的Web调试
    IntelIoT技术笔记Java/Eclipse
    IntelIoT技术笔记Maven
    Linux脚本(二)
    MINA
    360是神器
  • 原文地址:https://www.cnblogs.com/Key-Ky/p/3608632.html
Copyright © 2020-2023  润新知