繁体   English   中英

如何像一组命令一样逐行读取文本文件

[英]How to read a text file line by line like a set of commands

我有一个文本文件,其中写入了函数名称以及诸如“插入3”之类的参数,在该文件中,我需要分别读取插入内容和3,才能使用参数3调用函数插入。

到目前为止,我已经打开了文件,并在文件上调用了.readlines(),以将每一行分成每行文本的列表。 我现在正在努力寻找一种将.split()递归应用于每个元素的方法。 我要通过函数式编程来做到这一点,而不能使用for循环来应用.split()函数。

def execute(fileName):
    file = open(fileName + '.txt', 'r').readlines()
    print(file)
    reduce(lambda x, a: map(x, a), )

我想每行分别使用不同数量的参数,因此我可以调用测试脚本并运行每个函数。

嘿,我刚刚在repl.it上编写了代码,您应该检查一下。 但这里是故障。

  1. 从文件中读取每一行
  2. 现在,您应该有一个列表,其中每个元素都是文件中的新行

     lines = ["command argument", "command argument" ... "command argument"] 
  3. 现在,遍历列表中的每个元素,并在其中将元素拆分为“”(空格字符),并将其附加到新列表中,所有命令及其各自的参数将存储在该列表中。

     for line in lines: commands.append(line.split(" ")) 
  4. 现在命令列表应该是一个包含数据的多维数组,例如

     commands = [["command", "argument"], ["command", "argument"], ... ["command", "argument"]] 
  5. 现在您可以遍历每个子列表,其中索引0的值是命令,索引1的值是参数。 之后,您可以使用if语句来检查要使用哪种数据类型作为参数运行的命令/函数

这里是整个代码:

    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.

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