Skip to main content
 首页 » 编程设计

python之多次出现的单词的 NLTK 索引

2025年05月04日7落叶

我正在尝试使用 python 查找以下文本中单词“the”的索引

sent3 = ['In', 'the', 'beginning', 'God', 'created', 'the', 'heaven', 'and', 'the', 'earth', ' .']

如果我执行 sent3.index('the'),我会得到 1,这是单词第一次出现的索引。我不确定的是如何找到其他时间出现“the”的索引。有谁知道我该怎么做?

谢谢!

请您参考如下方法:

[i for i, item in enumerate(sent3) if item == wanted_item] 

演示:

>>> sent3 = ['In', 'the', 'beginning', 'God', 'created', 'the', 'heaven', 'and', 'the', 'earth', '.'] 
>>> [i for i, item in enumerate(sent3) if item == 'the'] 
[1, 5, 8] 

enumerate只是从一个可迭代对象构造一个元组的列表,由它们的值和它们对应的索引组成。我们可以使用它来检查该值是否是我们想要的,如果是,则从中提取索引。