根据你的评论,我认为你正在努力实现以下目标: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
这定义了接受参数的函数,以便以后可以重用它们。然后,您需要询问用户在处理数据时使用哪个函数,因此:
^{pr2}$
最后,您可以加载文件,逐行读取,拆分并按用户决定的函数进行处理: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
当然,您可以在以后做进一步的处理。在
更新-下面是对上述代码的一个简单测试,给定文件test_file.txt,其中包含:tokenized line 1
tokenized line 2
tokenized line 3
和file_name = "test_file.txt"在文件中定义,而函数定义为: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))
如果执行代码,则输出/跟踪如下: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']