1
def find_acronym():
    # if search term in database returns acronym and expansion
    for abbr, text in acronyms.items():
        if abbr == search_analyte.get():
            expansion.insert(0.0,'{0:>6}: {1: <10}\n'.format(abbr, text))
        elif str(search_analyte.get()) in text:
            expansion.insert(0.0,'{0:>6}: {1: <10}\n'.format(abbr, text))

    # if search term not in database , returns message DOES NOT WORK PROPERLY!     
    if search_analyte.get() not in text or abbr != search_analyte.get():
        expansion.insert(0.0,'"{0}"{1} \n {2}\n'.format(search_analyte.get(),' is  not in the database.','Add,if appropriate'))

我使用此功能搜索首字母缩略词词典及其相关的扩展含义,格式为{ ACRONYM: text details, ACRONYM2: its test,...}

该算法的工作原理是它检索任何搜索项的首字母缩写词和文本,但它也总是从最后一个 if 条件返回文本消息,以发现该项目是否在数据库中。我显然不合逻辑,或者我不明白循环在 Python 中是如何工作的。

4

2 回答 2

1

如果我了解您想要实现的目标,这是一种方法:

def find_acronym():
    found=False
    # if search term in database returns acronym and expansion
    for abbr, text in acronyms.items():
        if abbr == search_analyte.get():
            found=True
            expansion.insert(0.0,'{0:>6}: {1: <10}\n'.format(abbr, text))
        elif str(search_analyte.get()) in text:
            found=True
            expansion.insert(0.0,'{0:>6}: {1: <10}\n'.format(abbr, text))

    # if search term not in database , returns message DOES NOT WORK PROPERLY!     
    if not found:
        expansion.insert(0.0,'"{0}"{1} \n {2}\n'.format(search_analyte.get(),' is  not in the database.','Add,if appropriate'))
于 2013-05-08T10:30:55.953 回答
1

你现在拥有它的方式,最后一个测试是在 FOR 循环完成运行的,所以你不能再比较abbrtext有用了。

你想要这样的东西:

def find_acronym():

    found = False

    # if search term in database returns acronym and expansion
    for abbr, text in acronyms.items():
        if abbr == search_analyte.get():
            expansion.insert(0.0,'{0:>6}: {1: <10}\n'.format(abbr, text))
            found = True
        elif str(search_analyte.get()) in text:
            expansion.insert(0.0,'{0:>6}: {1: <10}\n'.format(abbr, text))
            found = True

    # if search term not in database    
    if not found:
        expansion.insert(0.0,'"{0}"{1} \n {2}\n'.format(search_analyte.get(),' is  not in the database.','Add,if appropriate'))
于 2013-05-08T10:26:49.570 回答