猿问

带有 str 和字节码对象的 Python3 错误

所以我尝试编写一个简单的函数来清理文本并对其进行总结:


def getTextWaPo(url):

page = urllib2.urlopen(url).read().decode('utf8')

soup = BeautifulSoup(page, "lxml")

text = ' '.join(map(lambda p: p.text, soup.find_all('article')))

return text.encode('ascii', errors='replace').replace("?"," ")

但是对于这段代码,我收到了这个错误:


  File "Autosummarizer.py", line 12, in getTextWaPo

  return text.encode('ascii', errors='replace').replace("?"," ")

  TypeError: a bytes-like object is required, not 'str'


  line 12 ==> text = getTextWaPo(articleURL)

我该怎么办?


HUWWW
浏览 194回答 2
2回答

桃花长相依

您必须将最后一行更改     return text.encode('ascii', errors='replace').replace("?"," ")为,     return text.encode('ascii', errors='replace').replace(b"?", b" ")因为在encode()您操作之后bytes,并且必须用其他字节替换字节。
随时随地看视频慕课网APP

相关分类

Python
我要回答