这是我的以下代码
import os
import string
#(Function A) - that will take in string as input and update the master dictionary
def counter(file):
word_counter = dict()
f = open(file, "rt")
words = f.read().split()
words= filter(lambda x: x.isalpha(), words)
for word in words:
if word in word_counter:
word_counter[word] += 1
else:
word_counter[word] = 1
return word_counter
# outside of Function
master = dict()
filelist=[os.path.join('medline',f) for f in os.listdir('medline')]
for file in filelist:
master.update(counter(file))
#Function B - Passed the mass dictionary A and outputed the top 3 words
def sort_dict(A):
remove_duplicate = []
new_list = dict()
for key, val in A.items():
if val not in remove_duplicate:
remove_duplicate.append(val)
new_list[key] = val
new_list = sorted(new_list.items(), key = lambda word_counter: word_counter[1], reverse = True)
print (f'Top 3 words for the master dictionary:', new_list[:3])
sort_dict(master)
问题是我无法使用更新功能(拼图规则)。
我需要使用从我迭代的目录中的每个文件生成的输出字典(函数 A)来更新这些函数之外的主字典。我只允许使用这些模块,并且无法将其转换为列表来附加它们,然后从中创建字典。我真的被这个问题困扰了,不知道如何将从函数 A 获得的输出放入字典中,以便在不违反规则的情况下用于函数 B。
慕仙森
相关分类