[英]Error: a bytes-like object is required, not 'str'
I was playing around with some code i found online. 我在玩一些我在网上找到的代码。 It's in Python 2. When i ran the code in Python 3, it gives me this error: a byte-like object is required, not 'str'. 它在Python 2中。当我在Python 3中运行代码时,它给了我这个错误:需要一个类似字节的对象,而不是'str'。 can someone help me fix this? 有人可以帮我解决这个问题吗? thank you very much 非常感谢你
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)))
Just cast line
into str
and error will be gone 只需将line
str
转换为str
,错误就会消失
line = line.replace('\r', ' ').replace('\n', ' ')
to 至
line = str(line).replace('\r', ' ').replace('\n', ' ')
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.