zoukankan      html  css  js  c++  java
  • python处理中文编码

    python2 读取excle中的数据时,对于汉字的读取报错:

    代码:data[num][4]={"content": "测试"}

            data=data[num][4]

    UnicodeEncodeError: 'ascii' codec can't encode characters in position 13-14: ordinal not in range(128)
     
     
    原因:中文编码出了问题
         python里面默认字符串都是ASCII编码,是string类型,在字符串前面加‘u'前缀可以直接声明Unicode字符串,
         但是如果处理的字符串里面出现非ascii码表示的字符(汉字),就只能转换成Unicode 
    1.decode(),将其他边编码的字符串转换成unicode编码,如str1.decode('gb2312'),表示将gb2312编码的字符串str1转换成unicode编码;
    2.encode(),将unicode编码转换成其他编码的字符串,如str2.encode('gb2312'),表示将unicode编码的字符串str2转换成gb2312编码;
    3.unicode(),同decode(),将其他编码的字符串转换成unicode编码,如unicode(str3, 'gb2312'),表示将gb2312编码的字符串str3转换成unicode编码。
          转码的时候一定要先搞明白字符串str是什么编码,然后decode成unicode,最后再encode成其他编码。
          另外,对一个unicode编码的字符串在进行解码会出错,所以在编码未知的情况下要先判断其编码方式是否为unicode,可以用isinstance(str, unicode)。
          不仅是中文,以后处理含非ascii编码的字符串时,都可以遵循以下步骤:
    1、确定源字符的编码格式,假设是utf8;
    2、使用unicode()或decode()转换成unicode编码,如str1.decode('utf8'),或者unicode(str1, 'utf8');
    3、把处理后字符串用encode()编码成指定格式。


    普通字符串可以用多种方式编码成Unicode字符串,具体要看你究竟选择了哪种编码:
    unicodestring = u"Hello world"
    # 将Unicode转化为普通Python字符串:"encode"
    utf8string = unicodestring.encode("utf-8")
    asciistring = unicodestring.encode("ascii")
    isostring = unicodestring.encode("ISO-8859-1")
    utf16string = unicodestring.encode("utf-16")
    # 将普通Python字符串转化为Unicode:"decode"
    plainstring1 = unicode(utf8string, "utf-8")
    plainstring2 = unicode(asciistring, "ascii")
    plainstring3 = unicode(isostring, "ISO-8859-1")
    plainstring4 = unicode(utf16string, "utf-16")
    assert plainstring1 == plainstring2 == plainstring3 == plainstring4



    修改后:data=data[num][4].encode('utf-8')

    成功运行
     
  • 相关阅读:
    python学习day15 内置函数
    python学习day14 生成器表达式
    python学习day13 迭代器,生成器
    python学习day12 装饰器进阶
    gulp管理angular2项目 配置文件
    angular2 基于webpack环境搭建
    jQuery dataTable 操作个人使用总结
    报错:Could not reserve enough space for object heap error
    CSS布局之圣杯布局和双飞翼布局
    CSS 之 Position定位
  • 原文地址:https://www.cnblogs.com/reblues/p/5577838.html
Copyright © 2011-2022 走看看