[英]Counting the word frequency in two list and output it in a dictionary
首先感謝您的點擊。
我只是一個初學者,沒有任何背景。
所以我有兩個單詞列表,一個是清單,另一個是一種文章,
我需要做的就是用checklist里的詞來檢查文章,看看它重復了多少次。
這是我寫的:
我的想法是使用 for 循環在第一個列表中取一個單詞並用它與第二個列表中的每個單詞進行比較,並在第一個列表中取另一個單詞並用它與第二個列表中的每個單詞進行比較,直到第一個list的話全搞定了。
我的代碼有什么問題?
任何人都可以對我的代碼提出一些建議。
一些錯誤處理可以直接修復您的代碼。 您看,您的代碼嘗試向不存在的鍵添加數字。 然后,如果單詞不在其中,它會在 1 處創建該值嗎?
試試這個:
def check_lists(listA,listB):
dictionary={}
for x in listA:
for y in listB
if x == y:
try:
dictionary[x]+=1
except KeyError:
dictionary[x]=1
return dictionary
這基本上需要兩個列表,並將 listA 中的每個值與 listB 中的每個值進行比較。 然后它嘗試向字典中的鍵添加一個,如果鍵不存在(因此使用try
和except
語句),則創建一個鍵並添加一個。
像這樣調用它:
check_dict=check_lists(joylist,poslist)
如果我正確理解您的帖子,您有一篇文章(或一長串單詞,在您的示例中稱為joylist
)並且您想提取其中一部分(在您的情況下為poslist
)的poslist
?
查看您當前的解決方案,您將通過更多的工作(@Agent Biscuit 的解決方案)獲得您想要的解決方案,但這不是最有效的解決方案,因為您每次都會迭代整個關鍵字列表,而您不這樣做不需要做。 由於您無論如何都在使用字典,因此您不妨預先加載它:
# Create a new dictionary from the checklist with counts of 0
word_counts = {x: 0 for x in poslist}
# Iterate over all the words in the article
for word in joylist:
# Check if the word is one we care about tracking. If it is then
# increment the count associated with that word by one
if word in word_counts:
word_counts[word] += 1
如果您不想使用列表初始化來創建字典,那么我們也可以從空字典中執行此操作:
# Create the word-count dictionary from our list of keywords
word_counts = dict()
for word in poslist:
word_counts[word] = 0
# Iterate over all the words in the article
for word in joylist:
# Check if the word is one we care about tracking. If it is then
# increment the count associated with that word by one
if word in word_counts:
word_counts[word] += 1
最后,如果您想過濾掉零計數,那么您也可以這樣做:
for k in list(word_counts.keys()):
if word_counts[k] == 0:
del word_counts[k]
您可以使用 dict 的 get 方法。
poslist = ['a', 'b', 'c', 't']
joylist = ['a', 'd', 'b', 'n', 'a', 'd', 'x', 'm']
c = {}
for j in joylist:
if j in poslist:
c[j] = c.get(j, 0) + 1
else:
c[j] = c.get(j, 0)
print(c)
輸出:
{'a': 2, 'd': 0, 'b': 1, 'n': 0, 'x': 0, 'm': 0}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.