Python字典返回值具有最大值并重新定义值

时间:2013-11-06 19:19:07

标签: python python-3.x dictionary

import ast # needed to read text as a dictionary
#import operator # needed to find maximum value
def define_words():
    '''
    Finds the word with the most occurences
    Asks for a definition
    Replaces entry in working dictionary
    Writes to a new final dictionary

    '''
    with open('/Users/admin/Desktop/Dante Dictionary/parole_di_dante.txt','r', encoding = "utf-8") as dic:
        dante_dict = ast.literal_eval(dic.read())# reads text as a dictionary
        #key_to_find = ''
        #definition = ''

        key_to_find = max(dante_dict.items(), key=operator.itemgetter(1))[0]
        print('The word needing to be defined is ', key_to_find)

        definition = input('Definition ? : ')
        for key_to_find in dante_dict.keys():
            #if key == key_to_find:
            dante_dict[key_to_find] = definition


    with open('/Users/admin/Desktop/Dante Dictionary/parole_di_dante.txt', 'w', encoding = 'utf-8') as outfile:
        outfile.write(str(dante_dict))

    with open('/Users/admin/Desktop/Dante Dictionary/final_dante_dictionary.txt', 'w', encoding = 'utf-8') as finalfile:
        finalfile.write(str(dante_dict))

我正在使用以上格式从字典中返回:

{'sicuramente,': 11, 'beatitudo,': 11, 'concetti:': 15, 'ello:': 15, 'ello;': 16, 'favella,': 33, 'fene.': 13, 'ello,': 22, 'spira,': 66,'che': 560,…}

然而,当我运行上述“程序”时,请说出我定义为“那个”的“che”这个词,返回的是:

{'sicuramente,': 'that', 'beatitudo,': 'that', 'concetti:': 'that', 'ello:': 'that', 'ello;': 'that', 'favella,': 'that', 'fene.': 'that', 'ello,': 'that', 'spira,': 'that','che': 'that'…} instead of changing only the entry that I want to edit.

显然我做的事情很愚蠢。我也不是说我没有设法删除标点符号。感谢你的帮助。谢谢

1 个答案:

答案 0 :(得分:0)

您不使用以下代码行:

key_to_find = max(dante_dict.items(), key=operator.itemgetter(1))[0]

在这里你将所有单词设置为相同的定义。

    definition = input('Definition ? : ')
    for key_to_find in dante_dict.keys(): 
        #if key == key_to_find:
        dante_dict[key_to_find] = definition

这有帮助吗?