我目前正在使用python创建语法分析器,该语法分析器将ada程序读取为txt文件,我需要读取数组中的每个元素并将其分配给打印内容。
这是我读取文件并将其放入数组中的代码
with open("resultForOne.txt", "r") as ins:
array = []
for line in ins:
array.append(line)
这就是我打印数组时得到的东西
['lexeme is function _____Token is keyword\n', 'lexeme is a _____Token is identifiers\n', 'lexeme is ( _____Token is symbol\n', 'lexeme is ) _____Token is symbol\n', 'lexeme is x _____Token is identifiers\n', 'lexeme is = _____Token is symbol\n', 'lexeme is 1 _____Token is const\n', 'lexeme is print _____Token is keyword\n', 'lexeme is ( _____Token is symbol\n', 'lexeme is x _____Token is identifiers\n', 'lexeme is ) _____Token is symbol\n', 'lexeme is end _____Token is keyword']
我想阅读每个词素并分配给它打印一些东西
答案 0 :(得分:0)
从您的代码中,我认为您正在寻找阅读行
with open("resultForOne.txt", "r") as ins:
array_ = []
for line in ins.readlines():
array_.append(line.strip() )
如果是这样,那么
with open("resultForOne.txt", "r") as ins:
array_ = [i.strip() for i in ins.readlines()]
您可以在阅读过程中或之后进行打印
for item in array_:
print(f'[INFO] -> {item}')
如果您想在处理过程中做
with open("resultForOne.txt", "r") as ins:
array_ = []
for line in ins.readlines():
print(f'[INFO] -> appending {line.strip()}')
array_.append(line.strip() )
希望这会有所帮助