我正在玩一些我在网上找到的代码。它在 Python 2 中。当我在 Python 3 中运行代码时,它给了我这个错误:需要一个类似字节的对象,而不是“str”。有人可以帮我解决这个问题吗?非常感谢您
import urllib.request as ur
text =
ur.urlopen('https://raw.githubusercontent.com/ryanmcdermott/trump-
speeches/master/speeches.txt')
words = []
for line in text:
line = line.decode('utf-8-sig', errors='ignore')
line = line.encode('ascii', errors='ignore')
line = line.replace('\r', ' ').replace('\n', ' ')
new_words = line.split(' ')
new_words = [word for word in new_words if word not in ['', ' ']]
words = words + new_words
print('Corpus size: {0} words.'.format(len(words)))
Run Code Online (Sandbox Code Playgroud)
小智 8
只需line投入str,错误就会消失
line = line.replace('\r', ' ').replace('\n', ' ')
Run Code Online (Sandbox Code Playgroud)
到
line = str(line).replace('\r', ' ').replace('\n', ' ')
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
4995 次 |
| 最近记录: |