zoukankan      html  css  js  c++  java
  • python语言中的编码问题(续)

    上文提到了python开发中非常重要的两处设置。

    一个是编解码器的默认设置defaultencoding

    >>> import sys
    >>> sys.getdefaultencoding()
    'ascii'

    另一个是声明在python文件头部的代码编码方式coding

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

    这两处设置在python的str,unicode对象的encode和decode方法中,有非常重要的作用,直接影响到结果。下面的代码按照目前的设置进行,即defaultencoding为ascii,coding为utf-8

    str和unicode

    str是普通字符串,使用一般需要解码成unicode。unicode是unicode 字符串,默认使用unicode方式编码,使用一般需要解码成指定的格式。

    使用str()方法创建字符串。

    s = str('你们') #存储时按utf-8存储
    print repr(s)   #打印结果为'xe4xbdxa0xe4xbbxac'

    使用unicode()方法创建的是unicode字符串,也可使用u标记。创建unicode字符串时,需指定字符串编码方式,否则按defaultencoding对字符串进行编码。

    u1=u'你们'
    u2= unicode('你们')  
    print u1  #输出正确
    print u2  #存储时按utf-8存储,再按ascii编码,出错
    #UnicodeDecodeError: 'ascii' codec can't decode byte 0xe4 in position 0: ordinal not in range(128)
    
    u3 = unicode('你们','utf-8')  #先按utf-8编码存储,再按utf-8解码
    print u3 #输出正确
    print repr(u3) #打印结果是 u'u4f60u4eec'
    
    u4 = unicode('你们','gbk')  #先按utf-8编码存储,再按gbk解码
    print u4 #打印结果是 浣犱滑
    print repr(u4) #打印结果是 u'u6d63u72b1u6ed1' 是 浣犱滑 三个字的unicode编码

    总结,任何字符串在存储是按照指定的coding进行存储,在解码时如不指定编码方式,将按照defaultencoding对字符串进行编码。

    decode()和encode()

    str.decode()  用于将字符串解码成指定的格式,如果不指定编码方式,将使用默认的ascii编码方式进行编码。

    s = str('你们')
    print s.decode('utf-8') #输出正确
    print s.decode() #出错
    #UnicodeDecodeError: 'ascii' codec can't decode byte 0xe4 in position 0: ordinal not in range(128)

    unicode.encode() 用于将标准的unicode编码成指定的格式,如果不指定编码方式,将使用默认的 defaultencoding进行编码。

    u=u'你们'
    print u.encode('utf-8')  #输出正确
    print u.encode('gbk')  #输出乱码,编码时为utf-8,解码时为gbk
    print u.encode() #出错,编码时为utf-8,解码时为ascii
    #UnicodeEncodeError: 'ascii' codec can't encode characters in position 0-1: ordinal not in range(128)

    总结,str字符串存储和unicode字符串存储时,按照coding设置编码,str.decode() 把本身解码成指定格式,unicode.encode()把本身编码成指定格式,如果不指定编解码格式,将使用defaultencoding进行编解码。如果编码解码方式不一致,将会出错或乱码。

    另有str.encode() ,unicode.decode(),这两个方法没什么用。因为str是已经编码了的字符串,无需再次编码。unicode本身已经解码成unicode了,无需再次解码。但python的就是这么好玩,为了保持对称,设计了这两个方法。

    官方文档如此描述:str.encode(e) is the same as unicode(str).encode(e). This is useful since code that expects Unicode strings should also work when it is passed ASCII-encoded 8-bit strings(from Guido van Rossum) .

    这段话大概意思是说encode方法本来是被unicode调的,但如果不小心被作为str对象的方法调,并且这个str对象正好是ascii编码的(ascii这一段和unicode是一样的),也应该让他成功。这就是str.encode方法的一个用处。

    类似地,把光用ascii组成的unicode再decode是一样的道理,因为好像几乎任何编码里ascii都没变。因此这样的操作等于没做。 这些方法没什么用,实际使用中往往会出错,比如下面两个。

    str.encode() ,首先使用默认的编码方式将str进行编码,然后使用指定的方式将对象解码

    s.encode("utf-8") #等价于 s.decode(defaultencoding).encode("utf-8")

    unicode.decode(),首先使用默认的编码方式将对象进行解码,再用指定的方式将对象编码

    u.decode("utf-8") #等价于 u.encode(defaultencoding).decode("utf-8")

    关于requests库

    requests库在写网络爬虫的时候经常用到,使用起来非常方便。

    Request对象在访问服务器后会返回一个Response对象,这个对象将返回的Http响应字节码保存到content属性中。content本身是未编码的二进制数据,如果是文本文件,则自动按str的默认方式编码。

    Response对象还有一个属性text,它是一个unicode字符串对象。如果不加处理直接访问,常常会发生乱码。因为Response对象会通过另一个属性encoding来将content字节码编码成unicode,而这个encoding属性居然是responses自己猜出来的。

    官方文档:

    text
    Content of the response, in unicode.

    If Response.encoding is None, encoding will be guessed using chardet.

    The encoding of the response content is determined based solely on HTTP headers, following RFC 2616 to the letter. If you can take advantage of non-HTTP knowledge to make a better guess at the encoding, you should set r.encoding appropriately before accessing this property.

    responses 根据http头文件获取encoding设置,大多数情况是正确的,但有时也有例外。所以要么你使用content然后重新解码,要么把encoding设置正确。

    # -*- coding: UTF-8 -*-
    import requests
    url = "http://xxx.xxx.xxx" #gbk格式编码的网页
    response = requests.get(url)
    response.encoding = 'gbk'
    
    print response.content   #未编码的二进制数据,如果是文本文件,则自动按str的默认方式编码,此处按ascii编码,结果显示乱码,
    print response.content.decode('gbk') #按“gbk”编码之后,显示正确
    print response.text #显示正确

    (完)

  • 相关阅读:
    SELECT INTO 和 INSERT INTO SELECT 两种表复制语句
    jquery各种滚动
    IE屏蔽鼠标右键、禁止复制粘贴等功能
    java高级---->Thread之BlockingQueue的使用
    java基础---->多线程之synchronized(六)
    java基础---->java中字符编码问题(一)
    java基础---->多线程之wait和notify(八)
    java基础---->多线程之ThreadLocal(七)
    java基础---->多线程之interrupt(九)
    java高级---->Thread之Exchanger的使用
  • 原文地址:https://www.cnblogs.com/zhmhhu/p/6158619.html
Copyright © 2011-2022 走看看