查看: 1874|回复: 3

TypeError: initial_value must be str or None, not bytes.

[复制链接]

4

主题

37

帖子

98

积分

注册会员

Rank: 2

积分
98
发表于 2018-9-27 10:50:09 | 显示全部楼层 |阅读模式
在将代码从python2移植到3的过程中,我读取URL时会出现这个错误
TypeError: initial_value must be str or None, not bytes.
  1. import urllib
  2. import json
  3. import gzip
  4. from urllib.parse import urlencode
  5. from urllib.request import Request
  6. service_url = 'https://babelfy.io/v1/disambiguate'
  7. text = 'BabelNet is both a multilingual encyclopedic dictionary and a semantic network'
  8. lang = 'EN'
  9. Key  = 'KEY'

  10.     params = {
  11.         'text' : text,
  12.         'key'  : Key,
  13.         'lang' :'EN'

  14.         }

  15. url = service_url + '?' + urllib.urlencode(params)
  16. request = Request(url)
  17. request.add_header('Accept-encoding', 'gzip')
  18. response = urllib.request.urlopen(request)
  19. if response.info().get('Content-Encoding') == 'gzip':
  20.             buf = StringIO(response.read())
  21.             f = gzip.GzipFile(fileobj=buf)
  22.             data = json.loads(f.read())
  23. The exception is thrown at this line
  24. buf = StringIO(response.read())  
复制代码

回复

使用道具 举报

4

主题

33

帖子

88

积分

注册会员

Rank: 2

积分
88
发表于 2018-9-27 10:51:45 | 显示全部楼层
response.read()返回一个bytes实例,StringIO是一个只用于文本的内存流。使用BytesIO代替。
Python 3.0的新特性——文本vs数据而不是Unicode vs 8位,StringIO和cStringIO模块都消失了。相反,导入io模块并使用io。StringIO或io。BytesIO分别表示文本和数据。
回复

使用道具 举报

22

主题

107

帖子

266

积分

中级会员

Rank: 3Rank: 3

积分
266
发表于 2018-9-27 10:52:54 | 显示全部楼层
这看起来像是另一个python3字节vs. str问题。你的reponse是字节类型(python 3中的类型与str不同)。您需要首先使用response.read().decode('utf-8')说,然后在它上使用StringIO。或者,你可能想要使用BytesIO,就像有人说的那样——但是如果你希望它是str,首选的方法是先解码为str。
回复

使用道具 举报

44

主题

139

帖子

382

积分

论坛管理

Rank: 4

积分
382
发表于 2018-9-30 08:47:19 | 显示全部楼层
对啊最烦遇到这种错误了
回复

使用道具 举报

您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

快速回复 返回顶部 返回列表