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

2024-09-25 08:27:10 发布

您现在位置:Python中文网/ 问答频道 /正文

我已经为我的程序创建了一个菜单系统。我有保存在另一个文件,我没有在这里引用的功能。你知道吗

这是我的密码:

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")

输出:

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: 

所以,这个程序做了我想做的一切,但问题是它对我来说有点麻烦。如果我想访问“信息”,我必须输入“信息”,我不能偏离这一点,因为系统不会识别该条目。你知道吗

我想使它能够识别“0”或“信息”;用户输入的模糊匹配作为正确的输入会更好。你知道吗

有什么建议我可以这样做吗?你知道吗


Tags: csvinformationargsprintprogrammeinenpunktsuche
2条回答

不用做复杂的事情,我们可以使用带有输入数字和函数的字典。即:

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()

这是快速和更好的小输入集和易于维护。 通过在hauptmenu中使用小写字母并将用户的输入转换为小写,您可以使它更加友好。你知道吗

我想我找到了一个不错的解决方案,包括输入验证。你可以很容易地把它变成一个泛型函数。你知道吗

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()

相关问题 更多 >