亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

使用函數輸出更新主字典而不使用字典更新

使用函數輸出更新主字典而不使用字典更新

侃侃爾雅 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條經驗 獲得超8個贊

您尚未描述實際要求,但我懷疑您想要所有文件的字數統計。您的使用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 關注
  • 130 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號