[英]Saving n lines after string match in file to variable
I'm trying to write a script that can read through a text file and save specific lines as lists. 我正在尝试编写一个可以读取文本文件并将特定行另存为列表的脚本。 The text file looks something like this: 文本文件看起来像这样:
TRIAL1 TRIAL1
Energy: 54432 能量:54432
Coordinates: 坐标:
0.7 0.4 0.5 0.7 0.4 0.5
0.3 0.4 0.1 0.3 0.4 0.1
0.3 0.4 0.3 0.3 0.4 0.3
there are many more trials in the file (TRIAL2, TRIAL3 etc. with corresponding energy and coordinates), but I want to be able to select one particular trial and save its corresponding coordinates in a list (for later manipulation). 文件中还有更多试验(TRIAL2,TRIAL3等,具有相应的能量和坐标),但是我希望能够选择一个特定的试验并将其对应的坐标保存在列表中(以供以后操作)。
So far, I've written: 到目前为止,我写过:
with open('energy.txt') as f:
for line in f:
if 'TRIAL1' in line:
I'm unsure how to then skip the lines "Energy" and "Coordinates" line, and save only the coordinates to a variable. 我不确定如何跳过“能量”和“坐标”行,仅将坐标保存到变量。
Assuming the "TRIAL" blocks all look the same as your example (adapt to fit your script): 假设所有“ TRIAL”块都与您的示例相同(以适应您的脚本):
lines = """TRIAL1
Energy: 54432
Coordinates:
0.7 0.4 0.5
0.3 0.4 0.1
0.3 0.4 0.3
TRIAL2
Energy: 54432
Coordinates:
test1
test2
test3"""
# initialize our control variables
counter = 0
collect = False
for line in lines.splitlines():
if 'TRIAL2' in line:
# mark the beginning of the block
counter = 0
collect = True
continue
if not collect:
# nothing to do, go to next line
continue
else:
# count the lines
counter += 1
if 2 < counter < 6:
# use the 3rd, 4th and 5th line
print(line)
elif counter == 6:
# stop collection at the 6th line of the block
collect = False
I suggest making some assumptions about your input and just read each line that you expect to be there. 我建议对您的输入做一些假设,然后阅读您希望输入的每一行。 You can later go back to add error checking code that enforces your assumptions. 您稍后可以返回以添加用于执行假设的错误检查代码。 Something like this: 像这样的东西:
with open('energy.txt') as f:
while True:
trial = f.readline() # assume this line is "TRIAL#"
energy = f.readline() # assume this line is "ENERGY:..."
coordinates_label = f.readline() # assume this line is "Coordinates:"
coordinates = f.readline()
while "TRIAL" not in coordinates
# parse the coordinates here
To ignore a line, just don't assign f.readline()
to a variable. 要忽略一行,只需不要将f.readline()
分配给变量。 If there are really blank lines between each line of input, just add appropriate f.readline()
calls. 如果输入的每一行之间确实有空白行,只需添加适当的f.readline()
调用即可。
Note: improving the while True:
loop is left as an exercise for the reader. 注意:改进while True:
循环留给读者练习。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.