[英]compare words in two lists in python
我很感激有人幫助解決這個問題很簡單:我有一長串的單詞形式['word', 'another', 'word', 'and', 'yet', 'another']
。 我想將這些單詞與我指定的列表進行比較,從而查找目標單詞是否包含在第一個列表中。
我想輸出哪些“搜索”單詞包含在第一個列表中以及它們出現的次數。 我嘗試了類似list(set(a).intersection(set(b)))
- 但是它將單詞分開並比較字母。
如何在一個單詞列表中寫入與現有的長列表進行比較? 我怎樣才能輸出同時出現的頻率? 非常感謝你的時間和幫助。
>>> 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
列表中,它會將單詞以及出現的數量添加到結果列表中。
使用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})
現在,您可以遍歷新的單詞列表並檢查它們是否包含在此Counter-dictionary中,並且該值會在原始列表中顯示它們的出現次數:
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)]
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.