3
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- 尽管我已经(我认为)覆盖了文件,但仍附加更改的文本。

我究竟做错了什么?

4

1 回答 1

1

这是一个非常混乱的外观功能。首字母缩写词替换本身可以非常简单地完成:

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 字典写入文件的函数中调用它,或者对它执行任何其他操作,因为它不再与仅写入文件相关联。

于 2013-05-27T23:42:20.900 回答