簡體   English   中英

出現次數多的單詞的NLTK索引

[英]NLTK index of a word with mulitiple occurences

我正在嘗試使用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只是從一個可迭代對象構造一個元組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]

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM