简体   繁体   English

在文件中将字符串匹配后保存n行到变量

[英]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.

相关问题 在字符串匹配后将行插入文件 - Inserting lines to a file after a string match 将特定字符串后的所有行保存到单独的文件中 - Saving all lines in a file after a certain string to a separate file 在字符串匹配后复制特定行,并使用它们替换另一个文件中的其他行 - Copying specific lines after a string match and using them to replace other lines in another file 在文本文件中的n行之后触发循环 - Trigger loop after n lines in a text file 我正在尝试编写 python 脚本以在文件中查找超过 1000 行的字符串,并在该字符串匹配后删除几行 (10) - I am trying to write python script to find a string in file with more than 1000 lines and delete few lines (10) after that string match 在文件中的字符串匹配后,如何提取下一组行并继续迭代 - After a match of a string in a file, how to extract the next set of lines and continue iteration Python-原始文件超过N行后创建一个新文件 - Python - Create a new file after the original file exceeds N lines 使用“writeLines”python 方法保存后的预期文本文件行 - Expected text file lines after saving with "writeLines" python method Python urlretrieve在文件扩展名后使用&#39;\\ r \\ n&#39;保存文件 - Python urlretrieve saving files with ' \r\n ' after the file extension 正则表达式匹配变量字符后的字符串 - Regex to match the string after variable character
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM