Python 3.x: User Input to Call and Execute a Function
有许多类似的问题,但没有一个答案解决了我的问题。
我定义了几个解析大型数据集的函数。首先,我调用数据,然后将数据(在.txt中表示为行和列)组织到列表中,我将为各个数据条目编制索引。在此之后,我建立了我的函数,这些函数将一次一个地遍历列表。代码如下:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 | f = open(fn) for line in iter(f): entries = [i for i in line.split() if i] def function_one(): if entries[0] == 150: # do something def function_two(): if entries[1] == 120: # do something else def function_three(): if len(entries) > 10: # do something else |
等。
我试图提示用户,当每个函数返回关于数据集的不同内容时,他们希望执行什么函数。我的尝试如下:
1 2 3 4 5 | f_call = input('Enter Function Name: ') if f_call in locals().keys() and callable(locals()['f_call']): locals()['f_call']() else: print('Function Does Not Exist') |
运行脚本时,会提示我输入
我还尝试使用
任何帮助都将不胜感激。
根据你的评论,我认为你正在努力实现这样的目标:
1 2 3 4 5 6 7 8 9 10 11 | def function_one(data): if data[0] == 150: pass # do something def function_two(data): if data[1] == 120: pass # do something else def function_three(data): if len(data) > 10: pass # do something entirely different |
这定义了接受参数的函数,以便以后可以重用它们。然后,您要询问用户在处理数据时要使用哪个函数,因此:
1 2 3 4 5 6 7 | while True: # loop while we don't get a valid input user_function = input('Enter a function name to use: ') # ask the user for input if user_function in locals() and callable(locals()[user_function]): # if it exists... user_function = locals()[user_function] # store a pointer to the function break # break out of the while loop since we have our valid input else: print('Invalid function name, try again...') |
最后,您可以加载您的文件,逐行读取它,将其拆分并按用户决定的函数进行处理:
1 2 3 4 | with open(file_name,"r") as f: for line in f: entries = line.split() # no need to check for empty elements user_function(entries) # call the user selected function and pass `entries` to it |
当然,之后您可以做进一步的处理。
更新-这里是对上述代码的一个简单测试,给定文件
1 2 3 | tokenized line 1 tokenized line 2 tokenized line 3 |
文件中定义的
1 2 3 4 5 6 7 8 | def function_one(data): print("function_one called: {}".format(data)) def function_two(data): print("function_two called: {}".format(data)) def function_three(data): print("function_three called: {}".format(data)) |
如果执行代码,这是输出/跟踪:
1 2 3 4 5 6 | Enter a function name to use: bad_name_on_purpose Invalid function name, try again... Enter a function name to use: function_two function_two called: ['tokenized', 'line', '1'] function_two called: ['tokenized', 'line', '2'] function_two called: ['tokenized', 'line', '3'] |
要使代码正常工作,只需在调用时保持变量
1 2 3 4 5 | f_call = input('Enter Function Name: ') if f_call in locals().keys() and callable(locals()[f_call]): locals()[f_call]() else: print('Function Does Not Exist') |
它可能不是最有效的修复方法,但您可以使用类似的方法:
1 2 3 4 5 6 7 8 9 | f_call = raw_input('Enter Function Name: ') if f_call =="function_one": function_one() if f_call =="function_two": function_two() if f_call =="function_three": function_three() else: print('Function Does Not Exist') |