在Python中查找特定单词的句子索引(列表中的句子)

2024-03-28 14:50:37 发布

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

我当前有一个文件,其中包含一个

example = ['Mary had a little lamb' , 
       'Jack went up the hill' , 
       'Jill followed suit' ,    
       'i woke up suddenly' ,
       'it was a really bad dream...']

我想通过例子找到“醒”这个词的句子索引。 在这个例子中,答案应该是f(“wake”)=3。F是一个函数。在

我试着将每个句子标记化,以便首先找到单词的索引:

^{pr2}$

但我不知道如何最终得到单词的索引,以及如何将它与句子的索引链接起来。有人知道怎么做吗?在


Tags: 文件theexample单词例子句子jackup
3条回答

如果要求返回出现该词的第一句话,可以使用类似-

def func(strs, word):
    for idx, s in enumerate(strs):
        if s.find(word) != -1:
            return idx
example = ['Mary had a little lamb' , 
       'Jack went up the hill' , 
       'Jill followed suit' ,    
       'i woke up suddenly' ,
       'it was a really bad dream...']
func(example,"woke")
for index, sentence in enumerate(tokenized_sents):
    if 'woke' in sentence:
        return index

所有句子:

^{pr2}$

您可以迭代列表中的每个字符串,在空白处拆分,然后查看您的搜索词是否在该单词列表中。如果在列表理解中执行此操作,则可以向满足此要求的字符串返回一个索引列表。在

def f(l, s):
    return [index for index, value in enumerate(l) if s in value.split()]

>>> f(example, 'woke')
[3]
>>> f(example, 'foobar')
[]
>>> f(example, 'a')
[0, 4]

如果您喜欢使用nltk

^{pr2}$

相关问题 更多 >