import ast # needed to read text as a dictionary
import operator # needed to find term with maximum value
def define_words():
final_dict={}
with open('/Users/admin/Desktop/Dante Dictionary/experimental_dict.txt','r', encoding = "utf-8") as dic:
dante_dict = ast.literal_eval(dic.read())# reads text as a dictionary
print('the start length was: ', len(dante_dict)) # start length of source dictionary
key_to_find = max(dante_dict.items(), key=operator.itemgetter(1))[0]
print('The next word to define is ', key_to_find) # show which word needs defining
definition = input('Definition ? : ') # prompt for definition
for key in dante_dict.keys():
if key == key_to_find:
final_dict.update({key_to_find:definition})
dante_dict.pop(key_to_find)
print('the end length is : ' ,len(dante_dict))
print(dante_dict) # print source dictionary, modified
print(final_dict) # print dictionary with newly defined entry
with open('/Users/admin/Desktop/Dante Dictionary/experimental_dict.txt', 'w', encoding = 'utf-8') as outfile:
outfile.write(str(dante_dict)) # writes source dictionary minus newly-defined term
with open('/Users/admin/Desktop/Dante Dictionary/trial_dictionary.txt', 'w', encoding = 'utf-8') as finalfile:
finalfile.write(str(final_dict)) 我很抱歉重新发布了一个类似的问题,以回应我所得到的帮助。不知道如何添加修改。这件事我还是有问题。我的最终字典每次都被覆盖,而不是追加新定义的术语,因此字典只包含最后一个键:value对,我认为使用dict_namekey = value,新条目将被追加,而其他条目将保持不变。助赏
发布于 2013-11-07 18:15:08
您可以在每个函数调用中创建一个"final_dict“字典,其中只有一个"key_to_find”键。我理解(阅读注释),您希望您的函数保留以前调用的结果,并追加新的结果。
当函数返回时,函数的命名空间连同函数中的所有变量一起被销毁。但是,只要简单地将代码重新排列成两个函数,就可以保存现有的字典:
def collectDict():
# first initialize your final_dict and dante_dict dictionary
final_dict={}
with open('/Users/admin/Desktop/Dante Dictionary/experimental_dict.txt','r', encoding = "utf-8") as dic:
dante_dict = ast.literal_eval(dic.read())# reads text as a dictionary
# loop as many times you want:
(dante_dict,final_dict) = define_words(dante_dict,final_dict) # call the define_words function to update your dictionaries
# write your dictionaries
with open('/Users/admin/Desktop/Dante Dictionary/experimental_dict.txt', 'w', encoding = 'utf-8') as outfile:
outfile.write(str(dante_dict)) # writes source dictionary minus newly-defined term
with open('/Users/admin/Desktop/Dante Dictionary/trial_dictionary.txt', 'w', encoding = 'utf-8') as finalfile:
finalfile.write(str(final_dict))
def define_words(dante_dict,final_dict):
# your already written function without the initialization (first 3 lines) and file writing part
return(dante_dict,final_dict) # you return the dictionaries for the other function这是一个直截了当的解决方案,但请注意,类正是为您所要做的而设计的。
https://stackoverflow.com/questions/19841506
复制相似问题