如何在Python中完成此操作? Combining Lists of Word Frequency Data
假设我有两个A和B列表,并且都包含单词&频率降序的文件频率,我怎么能用Python做问题呢?
from FrequentWords import *
from WordFrequencies import * # makes the list with words&frequencies
L = WordFrequencies('file.txt')
words1 = L[0]
freqs1 = L[1]
L1 = computeWordFrequencies('file1.txt')
words2 = L1[0]
freqs2 = L1[1]
words = zip(*sorted(zip(L,L1)))
both1 = sorted(freqs1+freqs2,reverse=True)
common_words = set(words1) & set(words2)
frequency_common_words = both1
答案 0 :(得分:4)
我会使用collections.Counter
:
>>> from collections import Counter
>>> c = Counter()
>>> a = {'a': 2, 'b': 3}
>>> b = {'b': 3, 'c': 4}
>>> c.update(a)
>>> c.update(b)
>>> c
Counter({'b': 6, 'c': 4, 'a': 2})
答案 1 :(得分:0)
如果您的起始数据在字典中,则可行:
output_dict = {}
for k, v in first_dict:
if k in second_dict:
v = v + second_dict[k]
output_dict[k] = v
for k, v in second_dict:
if k not in first_dict:
output_dict[k] = v