将代码从python2
移植到3
时,从URL读取时出现此错误
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,它可以正常工作。
最佳答案
response.read()
返回bytes
的实例,而 StringIO
是仅用于文本的内存流。请改用 BytesIO
。
从What's new in Python 3.0 - Text Vs. Data Instead Of Unicode Vs. 8-bit
关于python - 带有StringIO的Python3错误: initial_value must be str or None,,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/31064981/