[英]How to read a text file line by line like a set of commands
I have a text file that has written a function name along with the parameters such as "insert 3" where I need to read the insert and 3 individually to call a function insert with parameter 3. 我有一个文本文件,其中写入了函数名称以及诸如“插入3”之类的参数,在该文件中,我需要分别读取插入内容和3,才能使用参数3调用函数插入。
I have so far opened the file and called .readlines() on it to separate each line into a list of each line of text. 到目前为止,我已经打开了文件,并在文件上调用了.readlines(),以将每一行分成每行文本的列表。 I am now struggling to find a way to apply .split() to each element recursively. 我现在正在努力寻找一种将.split()递归应用于每个元素的方法。 I am to do this with functional programming and I cannot use a for loop to apply the .split() function. 我要通过函数式编程来做到这一点,而不能使用for循环来应用.split()函数。
def execute(fileName):
file = open(fileName + '.txt', 'r').readlines()
print(file)
reduce(lambda x, a: map(x, a), )
I would like to use each line independently with different amounts of parameters so I can call my test script and have it run each function. 我想每行分别使用不同数量的参数,因此我可以调用测试脚本并运行每个函数。
Hey I just wrote the code on repl.it you should check it out. 嘿,我刚刚在repl.it上编写了代码,您应该检查一下。 But here is the breakdown. 但这里是故障。
Now you should a list where each element is a new line from the file 现在,您应该有一个列表,其中每个元素都是文件中的新行
lines = ["command argument", "command argument" ... "command argument"]
Now iterate through each element in the list where you split the element at the " " (space character) and append it to a new list where all the commands and their respective arguments will be stored. 现在,遍历列表中的每个元素,并在其中将元素拆分为“”(空格字符),并将其附加到新列表中,所有命令及其各自的参数将存储在该列表中。
for line in lines: commands.append(line.split(" "))
Now the commands list should be a multidimensional array containing data like 现在命令列表应该是一个包含数据的多维数组,例如
commands = [["command", "argument"], ["command", "argument"], ... ["command", "argument"]]
Now you can just iterate through each sub-list where value at index 0 is the command and value at index 1 is the argument. 现在您可以遍历每个子列表,其中索引0的值是命令,索引1的值是参数。 After this you can use if statements to check for what command/ function to run with what datatype as an argument 之后,您可以使用if语句来检查要使用哪种数据类型作为参数运行的命令/函数
HERE IS THE WHOLE CODE: 这里是整个代码:
command = []
with open("command_files.txt", "r") as f:
lines = f.read().strip().split("\n") # removing spaces on both ends, and spliting at the new line character \n
print(lines) # now we have a list where each element is a line from the file
# breaking each line at " " (space) to get command and the argument
for line in lines:
# appending the list to command list
command.append(line.split(" "))
# now the command list should be a multidimensional array
# we just have to go through each of the sub list and where the value at 0 index should be the command, and at index 1 the arguments
for i in command:
if i[0] == "print":
print(i[1])
else:
print("Command not recognized")
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.