【问题标题】:Python dictionary return value with greatest value and redefine valuePython字典返回最大值并重新定义值
【发布时间】:2013-11-06 19:19:07
【问题描述】:
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,…}

但是,当我运行上述“程序”时,对我定义为“that”的单词“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.

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

【问题讨论】:

    标签: python python-3.x dictionary


    【解决方案1】:

    你不要使用这行代码:

    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
    

    这有帮助吗?

    【讨论】:

    • 感谢您为我指明了正确的方向。不知道如何解决这个问题,但会解决的。
    猜你喜欢
    • 2016-04-14
    • 2016-05-19
    • 2011-07-26
    • 2019-04-22
    • 2014-05-18
    • 1970-01-01
    • 1970-01-01
    • 2023-01-30
    • 1970-01-01
    相关资源
    最近更新 更多