Requests 庫編碼問題及引出的 Python 編碼問題

Requests 編碼

在使用 requests 訪問微信接口的時候,requests 只根據 http headers 的信息來設置編碼集,文檔以下:git

response.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.

這邊就是說,咱們的選擇還有,當服務器不指定編碼集時,使用如下方式指定編碼,而後再將 text 輸出,輸出的爲 unicode。github

r.encoding = 'utf-8'
r.text

關於這個的話題的討論能夠看這裏。 當咱們使用urllib2.urlopen('http://www.baidu.com').read()時,返回的則是 str 格式。服務器

Python 2 編碼問題

# Python 2 默認賦值時爲字節串即 str 類型,此處的哈哈通過 utf-8 編碼之後變成了 \xe5\x93\x88\xe5\x93\x88,此時 len(x) == 6
>>> x="哈哈"
>>> x
'\xe5\x93\x88\xe5\x93\x88'
>>> type(x)
<type 'str'>
# 因爲儲存哈哈到 str 類型時通過了 utf-8 編碼,因此要想得到哈哈,就必須經過解碼,解碼後獲得 unicode 類型的字符串
>>> x.decode('utf-8')
u'\u54c8\u54c8'
# 呵呵在儲存的時候 u 指定了它是 unicode 類型,因此變量 y 是真正意義上的字符串,咱們能夠經過 encode 操做將它轉換爲 str 類型
>>> y=u"呵呵"
>>> y
u'\u5475\u5475'
>>> type(y)
<type 'unicode'>
>>> y.encode('utf-8')
'\xe5\x91\xb5\xe5\x91\xb5'
>>> type(y.encode('utf-8'))
<type 'str'>

Python 3 編碼問題

>>> x='哈哈'
# Python 3 中的 str 類型儲存的實際上是 Python 2 中的 unicode 字符串,便是真正意義上的字符串
>>> type(x)
<class 'str'>
# 經過 Python 2 同樣的方法,咱們能夠將一個 unicode 轉換爲一個 bytes 字節串,這裏 bytes 其實就是 Python 2 中的 str 類型。
>>> y = x.encode('utf=8')
>>> y
b'\xe5\x93\x88\xe5\x93\x88'
>>> type(y)
<class 'bytes'>
>>>

總結

  • Python 2 中 str 和 Python 3 中 bytes 是一個東西
  • Python 2 中 unicode 和 Python 3 中 str 是一個東西
  • 字符串編碼後獲得字節串,字節串解碼後獲得字符串
  • 打開文件使用 codecs.open() 能夠指定編碼格式
相關文章
相關標籤/搜索