Python3错误:initial_value必须是str或None

AMi*_*sra 46 python urllib urllib2 python-3.x

虽然从移植代码python23,我从一个URL读取时出现此错误

TypeError: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())
Run Code Online (Sandbox Code Playgroud)

此行引发异常

buf = StringIO(response.read())  
Run Code Online (Sandbox Code Playgroud)

如果我使用python2,它工作正常.

tyn*_*ynn 80

response.read()返回byteswhile 的实例StringIO是仅用于文本的内存中流.请BytesIO改用.

Python 3.0中的新功能 - 文本与 数据而不是Unicode Vs. 8位

StringIOcStringIO模块都没有了.而是导入io模块并分别使用io.StringIOio.BytesIO用于文本和数据.


gab*_*jit 18

这看起来像另一个python3 bytesvs. str问题.您的响应类型bytes(在python 3中不同str).你需要首先使用response.read().decode('utf-8')say然后使用StringIO它将它变成一个字符串.或者你可能想要BytesIO像有人说的那样使用- 但是如果你期望它,那么str首选的方法是decode进入str第一个.