2013-03-14 147 views
1

我很感謝某人在這方面的幫助,這可能很簡單:我有一長串單詞['word', 'another', 'word', 'and', 'yet', 'another']。我想將這些單詞與我指定的列表進行比較,從而查找目標單詞是否包含在第一個列表中。在Python中的兩個列表中比較單詞

我想輸出哪些「搜索」單詞包含在第一個列表中,以及它們出現的次數。我嘗試了一些類似list(set(a).intersection(set(b)))的東西 - 但它分開了單詞並比較了字母。

如何在單詞列表中編寫與現有的長列表進行比較?我怎樣才能輸出共現和頻率?非常感謝你的時間和幫助。

+0

你能發表一些你試過的代碼嗎? 'set(['word','another'])'評估爲'set(['word','another'])'並且不會將單詞分成字母。 – 2013-03-14 10:52:25

回答

3

預處理你的詞彙與Counter列表:

from collections import Counter 
a = ['word', 'another', 'word', 'and', 'yet', 'another'] 
c = Counter(a) 
# c == Counter({'word': 2, 'another': 2, 'and': 1, 'yet': 1}) 

現在你可以在你的新的單詞列表進行迭代,並檢查它們是否包含在此反字典中和值,讓你自己的容貌的數在最初的名單:

words = ['word', 'no', 'another'] 

for w in words: 
    print w, c.get(w, 0) 

它打印:

word 2 
no 0 
another 2 

或輸出它以列表:

[(w, c.get(w, 0)) for w in words] 
# returns [('word', 2), ('no', 0), ('another', 2)] 
+0

非常感謝。這兩種解決方案似乎都很好,但是我的代碼允許輸入sort [('S'),('t'),('o'),('c'),('k')]股票在sys.argv(2)。在執行程序時,我怎樣才能將更多的單詞輸入到可比較的列表中?並與你的兩個建議的解決方案,它比較字母,而不是整個字 conll = open(sys.argv [1],'r') targetword = str(sys.argv [2]) vocab = [] C =計數器(翻譯) 打印ç 爲w的targetword: \t \t \t \t打印瓦特,c.get(W,0) \t \t \t \t \t 打印[(W,vocab.count(瓦特))for w in set(vocab)if w in targetword] print targetword – 2013-03-18 13:21:38

5
>>> lst = ['word', 'another', 'word', 'and', 'yet', 'another'] 
>>> search = ['word', 'and', 'but'] 
>>> [(w, lst.count(w)) for w in set(lst) if w in search] 
[('and', 1), ('word', 2)] 

該代碼通過lst獨特元件基本上迭代,並且如果元件處於search列表,它與數量增加的話,沿發生,到結果列表。