[英]Python3 error: initial_value must be str or None, with StringIO
While porting code from python2
to 3
, I get this error when reading from a URL将代码从python2
移植到3
,从 URL 读取时出现此错误
TypeError: initial_value must be str or None, not bytes.类型错误:initial_value 必须是 str 或 None,而不是字节。
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())
The exception is thrown at this line在这一行抛出异常
buf = StringIO(response.read())
If I use python2, it works fine.如果我使用 python2,它工作正常。
response.read()
returns an instance of bytes
while StringIO
is an in-memory stream for text only. response.read()
返回一个bytes
实例,而StringIO
是仅用于文本的内存中流。 Use BytesIO
instead.改用BytesIO
。
From What's new in Python 3.0 - Text Vs.来自Python 3.0 的新增功能 - 文本 Vs。 Data Instead Of Unicode Vs. 数据而不是 Unicode Vs。 8-bit 8 位
The
StringIO
andcStringIO
modules are gone.StringIO
和cStringIO
模块消失了。 Instead, import theio
module and useio.StringIO
orio.BytesIO
for text and data respectively.相反,导入io
模块并分别将io.StringIO
或io.BytesIO
用于文本和数据。
This looks like another python3 bytes
vs. str
problem.这看起来像是另一个 python3 bytes
vs. str
问题。 Your response is of type bytes
(which is different in python 3 from str
).您的响应是bytes
类型(在 python 3 中与str
)。 You need to get it into a string first using response.read().decode('utf-8')
say and then use StringIO
on it.您需要先使用response.read().decode('utf-8')
say 将其转换为字符串,然后在其上使用StringIO
。 Or you may want to use BytesIO
as someone said - but if you expect it to be str
, preferred way is to decode
into an str
first.或者您可能BytesIO
有人说的那样使用BytesIO
- 但如果您希望它是str
,首选方法是先decode
为str
。
考虑使用 Six.StringIO 而不是 io.StringIO。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.