简体   繁体   English

错误:需要一个类似字节的对象,而不是'str'

[英]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.

相关问题 需要一个类似字节的对象,而不是'str' - 错误 - a bytes-like object is required, not 'str' - error Python 错误:需要类似字节的对象,而不是“str” - Python error:a bytes-like object is required, not 'str' Popen错误:需要类似字节的对象,而不是'str' - Popen error: bytes-like object is required, not 'str' TypeError:需要一个类似字节的对象,而不是'str':得到此错误 - TypeError: a bytes-like object is required, not 'str' : Getting this error 出现错误“TypeError: a bytes-like object is required, not 'str'”,但为什么呢? - Error "TypeError: a bytes-like object is required, not 'str'" appears, but why? 如何修复错误 TypeError: a bytes-like object is required, not 'str'? - How to fix error TypeError: a bytes-like object is required, not 'str'? Python错误:TypeError:需要一个类似字节的对象,而不是'str' - Python error: TypeError: a bytes-like object is required, not 'str' “需要类似字节的 object,而不是 str” Python 中的错误 - “A bytes-like object is required, not str” Error in Python python错误TypeError:需要一个类似字节的对象,而不是'str' - python error TypeError: a bytes-like object is required,not 'str' Python SocketServer 错误:TypeError:需要类似字节的对象,而不是“str” - Python SocketServer Error : TypeError: a bytes-like object is required, not 'str'
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM