Python字典编辑词条

标签 python python-3.x

def replace_acronym(): # function not yet implemented
    #FIND
    for abbr, text in acronyms.items():
        if abbr == acronym_edit.get():
            textadd.insert(0,text) 
    #DELETE
    name = acronym_edit.get().upper()
    name.upper()
    r =dict(acronyms)
    del r[name]
    with open('acronym_dict.py','w')as outfile:
        outfile.write(str(r))
        outfile.close() # uneccessary explicit closure since used with...
    message ='{0} {1} {2} \n '.format('Removed', name,'with its text from the database.')
    display.insert('0.0',message)

    #ADD
    abbr_in = acronym_edit.get()
    text_in = add_expansion.get()
    acronyms[abbr_in] = text_in
    # write amended dictionary
    with open('acronym_dict.py','w')as outfile:
        outfile.write(str(acronyms))
        outfile.close()
    message ='{0} {1}:{2}{3}\n  '.format('Modified entry', abbr_in,text_in, 'added')
    display.insert('0.0',message)

我正在尝试在我的 tkinter 小部件中添加编辑字典条目的功能。字典的格式为 {ACRONYM: text, ACRONYM2: text2...}

我认为该功能将实现的是在字典中找到条目,删除首字母缩略词及其相关文本,然后添加首字母缩略词和文本已更改为的任何内容。例如,如果我有一个条目 TEST: test 并且我想将它修改为 TEXT: abc 函数返回的是 TEXT: testabc - 尽管我(我认为)覆盖了文件,但仍附加更改的文本。

我做错了什么?

最佳答案

这是一个看起来很乱的函数。首字母缩写词替换本身可以非常简单地完成:

acronyms = {'SONAR': 'SOund Navigation And Ranging',
            'HTML': 'HyperText Markup Language',
            'CSS': 'Cascading Style Sheets',
            'TEST': 'test',
            'SCUBA': 'Self Contained Underwater Breathing Apparatus',
            'RADAR': 'RAdio Detection And Ranging',
           }

def replace_acronym(a_dict,check_for,replacement_key,replacement_text):
    c = a_dict.get(check_for)
    if c is not None:
        del a_dict[check_for]
        a_dict[replacement_key] = replacement_text
    return a_dict

new_acronyms = replace_acronym(acronyms,'TEST','TEXT','abc')

这非常适合我(在 Python 3 中)。你可以在另一个将 new_acronyms 字典写入文件的函数中调用它,或者用它做任何你想做的事情,因为它不再局限于只写入文件。

关于Python字典编辑词条,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16462549/

相关文章:

python - Flask API - 验证哈希请求

python代码错误(linux,网络抓取)奇怪的错误

python-3.x - 使用 python 为 elasticsearch 6.x 调用_analyze

python - 将新字符串添加到文本文件中特定行的末尾

python - 使用 Warnsdorff 规则的 Knight' tour 给出了奇怪大小的错误输出 moSTLy

python - 导入错误 : Missing DLL on Windows 7 when trying to import Python module

python - 向服务器 pyzmq 发送数据时出现问题

python - Softlayer API : change root password and ssh-key operation

python - 系列的链接过滤器

python-3.x - 使用python 3.6安装自定义构建tensorflow 1.12车轮时出错