簡體   English   中英

在列表字典中查找單詞的所有出現

[英]Finding All Occurrences of a Word in a Dictionary of Lists

我試圖找出某個單詞出現在哪些行號上。例如,我有以下列表的字典。 這里的每個列表都是段落中的一行。

{1: ['They', 'seek', 'him', 'here'], 
2: ['they', 'seek', 'him', 'there'], 
3: ['those', 'Frenchies', 'seek', 'him', 'everywhere']}

我想找到單詞“ him”出現的所有行。 很明顯,僅通過查看它就出現在第1,2,3行中,但是我如何讓我的輸出告訴我它出現在哪些行中?

如果您只想執行一次,則可以使用以下方法:

[k for (k, v) in d.items() if 'him' in v]

如果您打算多次進行此操作,建議您再建一個字典,將單詞映射到出現的行。

z={1: ['They', 'seek', 'him', 'here'], 
2: ['they', 'seek', 'him', 'there'], 
3: ['those', 'Frenchies', 'seek', 'him', 'everywhere']}

indices=[k for k in z if 'him' in z[k]]

您可以遍歷鍵並檢查每個列表中是否存在搜索詞組。 請查看此代碼是否有幫助:

searchPhrase = "him"
lines = []
for i in iDict:
    if(searchPhrase in iDict[i])
        lines.append(i)
print(lines)

這是簡單的解決方案。

d={1: ['They', 'seek', 'him', 'here'], 2: ['they', 'seek', 'him', 'there'], 3: ['those', 'Frenchies', 'seek', 'him', 'everywhere']}
word="him"
lines=[]
for i in d:
    if word in d[i]:
        lines.append(i)
print lines

暫無
暫無

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

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