为了账号安全,请及时绑定邮箱和手机立即绑定

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

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

侃侃尔雅 2023-08-15 17:18:27
这是我的以下代码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 wordsdef 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。
查看完整描述

1 回答

?
慕仙森

TA贡献1827条经验 获得超7个赞

您尚未描述实际要求,但我怀疑您想要所有文件的字数统计。您的使用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) + 1

if key in master:您可以使用master.get()默认值来代替使用。


查看完整回答
反对 回复 2023-08-15
  • 1 回答
  • 0 关注
  • 69 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信