使用函数输出更新主字典而不使用字典更新

这是我的以下代码


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。


侃侃尔雅
浏览 75回答 1
1回答

慕仙森

您尚未描述实际要求,但我怀疑您想要所有文件的字数统计。您的使用update()将用包含该单词的下一个文件中的计数来替换单词计数,并且最终每个单词仅从其最后一个文件中进行计数。您需要将当前文件中的计数添加到字典中已有的值。for file in filelist:    for key, val in counter(file).items():        master[key] = master.get(key, 0) + val您也可以在counter()函数本身中执行此操作,而不是返回字典。def counter(file):    f = open(file, "rt")    words = f.read().split()    words= filter(lambda x: x.isalpha(), words)            for word in words:        master[word] = master.get(word, 0) + 1if key in master:您可以使用master.get()默认值来代替使用。
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Python