2013-12-18 178 views
2

目前,我能夠打印出在句子列表中有匹配的字典項目。我寧願打印出句子列表中的元素。請建議實現此目標的最佳方法。以下是我的代碼。謝謝。Python比較兩個不同列表中的元素

sentences = "The book was awesome and envious","splendid job done by those guys", "that was an amazing sale" 

dictionary = "awesome","amazing", "fantastic","envious" 

##Find Matches 
for match in dictionary: 
    if any(match in value for value in sentences): 
     print match 
+1

句子一個新的列表,您似乎匹配對單詞的句子 - 你確定這是正確的? – DNA

+0

多數民衆贊成在我的想法,所以我把它作爲我的答案...但我不知道我明白他的問題陳述... –

+0

我有兩個名單: a - 包含關鍵字如[「無可挑剔」,「明顯」 ,「奇妙」,「顯而易見」]作爲列表中的元素 b - 包含諸如[「我無可挑剔」,「你太棒了」,「很明顯」,「很明顯」等句子的句子] 目標是使用字典列表作爲參考。 處理過程如下: 爲句子列表取一個元素,並針對字典列表中的每個元素運行它。如果存在任何元素,則將該句子吐出一個新列表 對句子列表中的每個元素重複步驟1。 – BlackHat

回答

1
all_words = re.sub("[^a-zA-Z]","",main_text).split() 
dictionary_words = open("dictionary.txt").read().split() 

print "words found:",set(all_words).intersection(dictionary_words) 
print "words not found:",set(all_words).difference(dictionary_words) 

是你lookign什麼?

,如果你有句子的列表,你想創建一個包含字典中的單詞,你可以這樣做

sentances_with_words_in_dict = [sentence for sentence in all_sentences if set(sentence.split()).intersection(dictionary_words)] 
+0

真棒。我會放棄這一點並讓你知道。感謝mucho的幫助。 – BlackHat

+0

你好喬蘭,我試過你的建議,但遇到了一個無止境的循環。問題出在我身上。我想我過分複雜了我的要求。我編輯了簡化代碼。請參閱上文。 – BlackHat