简体   繁体   English

关键字与字典中的函数相结合

[英]Keyword coupled with a function in a dictionary

I have created a menu system for my program.我为我的程序创建了一个菜单系统。 I have the functions saved in another file that I haven't referenced here.我将函数保存在另一个文件中,但我没有在此处引用。

Here is my code:这是我的代码:

print("\nHauptmenü\n")
hauptmenue = {"Information":programm_information,
              "Beenden": programm_beenden,
              "Hilfe":programm_erklaerung,
              "Trennzeichen":text_trennzeichen,
              "Lesen":csv_suchanfrage,
              "csv_suche":csv_suchanfrage}
while True:
    for menue_punkt in enumerate (hauptmenue):
        print(menue_punkt)
    eingabe = input("\nOption: bitte einen Menüpunkt eingeben: ")
    args = eingabe.split()
    if len(args) < 4:
        if args[0] in hauptmenue:
            key = args[0]
            hauptmenue[key]()
        else:
            print (eingabe," ist keine gültige Option.\n ")
            print("Hauptmenü\n")

output:输出:

Hauptmenü

(0, 'Information')
(1, 'Beenden')
(2, 'Hilfe')
(3, 'Trennzeichen')
(4, 'Lesen')
(5, 'csv_suche')

Option: bitte einen Menüpunkt eingeben: Information
Version : 1.0
Datum der letzten Version : 04.01.2020
(0, 'Information')
(1, 'Beenden')
(2, 'Hilfe')
(3, 'Trennzeichen')
(4, 'Lesen')
(5, 'csv_suche')

Option: bitte einen Menüpunkt eingeben: 

So, the program does everything that I want it to do, but the problem is that it is a bit cumbersome for me.所以,程序做了我想要它做的一切,但问题是它对我来说有点麻烦。 If I want to access "Information", I have to to enter "Information" and I can't deviate from that because the system won't recognize the entry.如果我想访问“信息”,我必须输入“信息”,我不能偏离它,因为系统不会识别该条目。

I want to make it so that it can recognize "0" or "Information";我想让它可以识别“0”或“信息”; a fuzzy match of the user's entry as a proper entry would be better.用户条目的模糊匹配作为正确条目会更好。

Any suggestions on how I could do this?关于我如何做到这一点的任何建议?

I think I found a decent solution, which includes input verification.我想我找到了一个不错的解决方案,其中包括输入验证。 You could easily make this into a generic function.你可以很容易地把它变成一个通用函数。

def programm_information():
    return None


def programm_beenden():
    return None


def programm_erklaerung():
    return None


def text_trennzeichen():
    return None


def csv_suchanfrage():
    return None


menu_options_dict = {"Information": programm_information,
                     "Beenden": programm_beenden,
                     "Hilfe": programm_erklaerung,
                     "Trennzeichen": text_trennzeichen,
                     "Lesen": csv_suchanfrage,
                     "csv_suche": csv_suchanfrage}

invalid_input_msg = 'Invalid choice, please try again. Press ENTER to continue.'

while True:
    print('Choose an option:')
    for num, elem in enumerate(menu_options_dict, start=1):
        print(f'{num}: {elem}')
    choice_str = input('Option: bitte einen Menüpunkt eingeben: ').strip()
    options_dict_res = menu_options_dict.get(choice_str)
    if options_dict_res:
        break
    else:
        try:
            choice_num = int(choice_str)
        except ValueError:
            input(invalid_input_msg)
        else:
            if 0 < choice_num <= len(menu_options_dict):
                options_dict_res = list(menu_options_dict.values())[choice_num - 1]
                break
            else:
                input(invalid_input_msg)

print(options_dict_res)
func_res = options_dict_res()

Instead of doing complicated things, we can use a dictionary with input-numbers and functions.我们可以使用带有输入数字和函数的字典,而不是做复杂的事情。 That is:那是:

hauptmenue = {"Information":programm_information,
              "Beenden": programm_beenden,
              "Hilfe":programm_erklaerung,
              "Trennzeichen":text_trennzeichen,
              "Lesen":csv_suchanfrage,
              "csv_suche":csv_suchanfrage}
inputmenu = {0 : "Information",
             1 : "Beenden",
             2 : "Hilfe",
             3 : "Trennzeichen",
             4 : "Lesen",
             5 : "csv_suche"}
while True:
    for choice, option in enumerate(inputmenu):
        print(choice, option)
    choice_str = input("\nOption: bitte einen Menüpunkt eingeben: ").strip() # strip removes leading n trailing white spaces.
    if choice_str.isalpha():
        #Everything is alphabet, so it must an option name.
        option = choice_str #Not needed, but writing to make it easy to understand
    else:
        option = inputmenu.get(int(choice_str), None) # gives None if choice not found.
    func = hauptmenue.get(option, False)
    if not func: func()

This is quick and better for small set of inputs and easy to maintain.这对于一小组输入来说是快速和更好的,并且易于维护。 You can make it more user-friendly by using lower-case letters in hauptmenu and conveting input of user to lowercase.您可以通过在 hauptmenu 中使用小写字母并将用户输入转换为小写来使其更加用户友好。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM