多出现词的NLTK索引

2024-10-05 14:32:01 发布

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

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

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

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

谢谢!在


Tags: andthein文本index时间单词created
2条回答
[i for i, item in enumerate(sent3) if item == wanted_item]

演示:

^{pr2}$

^{}只是从iterable构造一个元组的list,由它们的值和相应的索引组成。我们可以用这个来检查这个值是否是我们想要的,如果是的话,从中提取索引。在

>>> from collections import defaultdict
>>> sent3 = ['In', 'the', 'beginning', 'God', 'created', 'the', 'heaven', 'and', 'the', 'earth', '.']
>>> idx = defaultdict(list)
>>> for i,j in enumerate(sent3):
...     idx[j].append(i)
... 
>>> idx['the']
[1, 5, 8]

相关问题 更多 >