Python在语料库中查找以“able”结尾的单词

2024-10-05 10:09:33 发布

您现在位置:Python中文网/ 问答频道 /正文

我的任务是将语料库标记为单词,然后找到以“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个结果。我做错了什么


Tags: in标记importrestringlineable单词
3条回答

我发现不使用re.findall就可以完成任务:

able_words = [w for w in set(guten_words) if w.endswith('able')]

您可以尝试在字符串列表中搜索,但不能在字符串中搜索(按要求: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], [])

试试这个:

list(filter(lambda x:x.re.findall(r'able$', x), guten_words))

guten_words是一个列表

尝试打印guten_words的类型

print(type(guten_words))

相关问题 更多 >

    热门问题