确定句子中是否有单词列表?

2024-05-08 20:07:06 发布

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

有没有一种方法(Pattern或Python或NLTK等)可以检测出一个句子中有一个单词列表。

The cat ran into the hat, box, and house.| The list would be hat, box, and house

这可以是字符串处理,但我们可能有更多的通用列表:

The cat likes to run outside, run inside, or jump up the stairs.

List=run outside, run inside, or jump up the stairs.

这可能在段落的中间或句子的结尾,这会使事情更加复杂。

我已经使用Pattern for python有一段时间了,我没有看到一种方法来实现这一点,我很好奇Pattern或nltk(自然语言工具包)是否有一种方法。


Tags: orandthe方法runbox列表hat
3条回答

使用from nltk.tokenize import sent_tokenize怎么样?

sent_tokenize("Hello SF Python. This is NLTK.")
["Hello SF Python.", "This is NLTK."]

然后你可以这样使用这个句子列表:

for sentence in my_list:
  # test if this sentence contains the words you want
  # using all() method 

更多信息here

根据我从你的问题中得到的信息,我想你想查一下你名单上的所有单词是否都出现在一个句子中。

一般来说,要搜索列表元素,可以在句子中使用all函数。如果其中的所有参数都为true,则返回true。

listOfWords = ['word1', 'word2', 'word3', 'two words']
sentence = "word1 as word2 a fword3 af two words"

if all(word in sentence for word in listOfWords):
    print "All words in sentence"
else:
    print "Missing"

输出

"All words in sentence"

我想这可能符合你的目的。如果没有,你可以澄清。

all(word in sentence for word in listOfWords)

相关问题 更多 >