我有一個主詞典來保持整個語料庫的詞頻和個別詞典來保持每個文本文件的詞頻。我遍歷每個文件,生成每個文件的 WF,然后依次更新主詞典。我的代碼如下。有捷徑嗎?謝謝! master_dict = {} for txtfile in txtfiles: file_dict = {} file_dict = get_word_freq(txtfile) #A function is defined for k, v in file_dict.items(): if k in master_dict: master_dict[k] += v else: master_dict[K] = v
1 回答

繁花不似錦
TA貢獻1851條經驗 獲得超4個贊
您應該考慮使用 python 具有的“Counter”類。
from collections import Counter
words_a = 'one two three'
words_b = 'one two one two'
words_c = 'three four five'
a = Counter(words_a.split())
b = Counter(words_b.split())
c = Counter(words_c.split())
print(a + b + c)
# outputs Counter({'one': 3, 'two': 3, 'three': 2, 'four': 1, 'five': 1})
添加回答
舉報
0/150
提交
取消