在将代码从python2
移植到3
时,我在读取URL时遇到以下错误
TypeError: initial_value必须是字符串或无,而不是字节。
import urllib
import json
import gzip
from urllib.parse import urlencode
from urllib.request import Request
service_url = 'https://babelfy.io/v1/disambiguate'
text = 'BabelNet is both a multilingual encyclopedic dictionary and a semantic network'
lang = 'EN'
Key = 'KEY'
params = {
'text' : text,
'key' : Key,
'lang' :'EN'
}
url = service_url + '?' + urllib.urlencode(params)
request = Request(url)
request.add_header('Accept-encoding', 'gzip')
response = urllib.request.urlopen(request)
if response.info().get('Content-Encoding') == 'gzip':
buf = StringIO(response.read())
f = gzip.GzipFile(fileobj=buf)
data = json.loads(f.read())
异常在此行抛出
buf = StringIO(response.read())
如果我使用python2,它工作得很好。
发布于 2015-06-26 07:28:52
response.read()
返回bytes
的一个实例,而StringIO
是一个仅用于文本的内存中的流。请改用BytesIO
。
来自What's new in Python 3.0 - Text Vs. Data Instead Of Unicode Vs. 8-bit
StringIO
和cStringIO
模块消失了。相反,您可以导入io
模块,并使用io.StringIO
或io.BytesIO
分别处理文本和数据。
发布于 2015-06-26 07:31:56
这看起来像是另一个python3 bytes
与str
的问题。您的响应类型为bytes
(在Python3中与str
中的类型不同)。您需要首先使用response.read().decode('utf-8')
将其转换为字符串,然后对其使用StringIO
。或者你可能想要像别人说的那样使用BytesIO
--但是如果你希望它是str
,首选的方法是先decode
到一个str
中。
发布于 2019-07-08 17:05:28
考虑使用six.StringIO而不是io.StringIO。
https://stackoverflow.com/questions/31064981
复制相似问题