zoukankan      html  css  js  c++  java
  • Python 中文编码问题小结

    1. 下面的语句要放在代码开头,指定文件编码, 可以识别 脚本中的所有字符和中文。

    # -*- coding:utf-8 -*-

    2. codecd 编码转换

    如果想要读取文本中的中文,需要借助于codecs的一套open方法,而不是内置的open。

    #-*- coding:utf-8 -*-
    print '我是'
    import codecs
    
    f=codecs.open("e:/python/test_data/chinese.txt")
    content=f.read()
    f.close()
    
    if isinstance(content,unicode):
        print content.encode('utf-8')
        print "utf-8"
    else:
        print content.decode('gbk').encode('utf-8')

     上面是为了显示内部编码的转换,简便用法如下:

    chi1=codecs.open("e:/python/test_data/chinese.txt",'r','gbk')                 # 在打开时,指定文本的编码格式
    content1=chi1.read()
    print content1
    chi1.close()

    3. codecs 编码小结:

    gb2312/gbk 格式是中国标准的汉字编码格式,用于语言处理和编码转换。

    python的内部表示,是unicode编码。如果要做编码转换,需要:

                                                       decode                   encode

                                          source    ---------〉  unicode  ----------〉 target

    如果一个文件已经是unicode编码可以直接使用encode做编码转换。否则报错。例如:

     s=u'中文' 

    此时可以先判断其编码方式是否是unicode:

    isinstance(yourstr, unicode)     #用来判断是否为unicode 
  • 相关阅读:
    HierarchicalDataTemplate
    Prism技巧
    常用Exception
    netcore URL重新路径
    Nintendo Switch相册整理
    交换变量-不借助任何变量
    QCombobox样式stylesheet总结
    Qt新旧Moc方式升级功能
    QSS使用方法总结
    【QRegExp】QLineEdit屏蔽空格
  • 原文地址:https://www.cnblogs.com/skyEva/p/5749241.html
Copyright © 2011-2022 走看看