在将代码从python2迁移到python3时,当从URL中读取内容时,出现以下错误:
TypeError:initial_value必须是str或NoneType,而不是bytes类型。
TypeError:initial_value必须是str或NoneType,而不是bytes类型。
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,它可以正常工作。
url
的值?当我使用url = 'http://www.google.com'
时,代码对我来说可以正常运行。 - maxymoopandas.read_csv()
在ASCII输入上推断错误的编码而来到这里,请使用encoding='utf8'
或'latin1'
来强制它。 - smci