首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >Python字典返回值最大值和重定义值

Python字典返回值最大值和重定义值
EN

Stack Overflow用户
提问于 2013-11-07 03:19:07
回答 1查看 79关注 0票数 0
代码语言:javascript
复制
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))

我使用上面的代码从字典中返回如下格式:

代码语言:javascript
复制
{'sicuramente,': 11, 'beatitudo,': 11, 'concetti:': 15, 'ello:': 15, 'ello;': 16, 'favella,': 33, 'fene.': 13, 'ello,': 22, 'spira,': 66,'che': 560,…}

然而,当我运行上面的'programme',比如我定义为' that‘的单词'che’时,返回的结果是:

代码语言:javascript
复制
{'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.

我也不是说我没有设法删除标点符号。谢谢

EN

回答 1

Stack Overflow用户

发布于 2013-11-07 06:32:12

您不使用下面这行代码:

代码语言:javascript
复制
key_to_find = max(dante_dict.items(), key=operator.itemgetter(1))[0]

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

代码语言:javascript
复制
    definition = input('Definition ? : ')
    for key_to_find in dante_dict.keys(): 
        #if key == key_to_find:
        dante_dict[key_to_find] = definition

这有帮助吗?

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/19820858

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档