我的任务是将语料库标记为单词,然后找到以“able”结尾的单词。但是,会发生此错误
>>> import nltk
>>> import re
>>> from nltk.corpus import gutenberg as guten
>>> guten_words = guten.words('austen-emma.txt')
>>> len(guten_words)
192427
>>> able_words = re.findall(r'able$',guten_words)
Traceback (most recent call last):
File "<pyshell#5>", line 1, in <module>
able_words = re.findall(r'able$',guten_words)
File "C:\Program Files\Python37\lib\re.py", line 225, in findall
return _compile(pattern, flags).findall(string)
TypeError: expected string or bytes-like object
>>>
如果我尝试添加“str”来更正它,如下所示:
able_words = re.findall(r'able$',str(guten_words))
。。。我得到0个结果。我做错了什么
我发现不使用re.findall就可以完成任务:
您可以尝试在字符串列表中搜索,但不能在字符串中搜索(按要求:https://docs.python.org/3/library/re.html#re.findall)。 当您将列表强制转换为字符串时,会得到如下结果:[,…]
例如,如果它们是字符串,则应该在
"\n".join(guten_words)
中搜索。 或者刚找到单词=sum([my_func_to_list(re.findall(word)) for word in guten_words], [])
试试这个:
guten_words
是一个列表尝试打印
guten_words
的类型print(type(guten_words))
相关问题 更多 >
编程相关推荐