[英]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上編寫了代碼,您應該檢查一下。 但這里是故障。
現在,您應該有一個列表,其中每個元素都是文件中的新行
lines = ["command argument", "command argument" ... "command argument"]
現在,遍歷列表中的每個元素,並在其中將元素拆分為“”(空格字符),並將其附加到新列表中,所有命令及其各自的參數將存儲在該列表中。
for line in lines: commands.append(line.split(" "))
現在命令列表應該是一個包含數據的多維數組,例如
commands = [["command", "argument"], ["command", "argument"], ... ["command", "argument"]]
現在您可以遍歷每個子列表,其中索引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.