【问题标题】:How to read a text file line by line like a set of commands如何像一组命令一样逐行读取文本文件
【发布时间】:2019-09-01 10:15:41
【问题描述】:

我有一个文本文件,其中写入了函数名称以及参数,例如“插入 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), )

我想用不同数量的参数独立使用每一行,这样我就可以调用我的测试脚本并让它运行每个函数。

【问题讨论】:

    标签: python-3.x list file recursion functional-programming


    【解决方案1】:

    嘿,我刚刚在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")
    

    【讨论】:

      猜你喜欢
      • 2012-10-13
      • 2013-12-26
      • 1970-01-01
      • 2017-09-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多