zoukankan      html  css  js  c++  java
  • 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

      

  • 相关阅读:
    GDC2017:Framegraph-extensible-rendering-architecture-in-frostbite
    17072802(UE4的批量Import)
    16011301(统计指令数影响耗时)
    16080401(面向摄像机的Instance模型)
    UE4编译_201701
    17020701(AnimDynamic继续)
    Python过滤utf8mb4无效字符
    Windows下安装MySQL-python
    使用Pycharm更新Github项目(到源项目)
    python异常:error: command 'gcc' failed: No such file or directory
  • 原文地址:https://www.cnblogs.com/Key-Ky/p/3608632.html
Copyright © 2011-2022 走看看