gpt4 book ai didi

Python 在文件中的模式之后迭代 grep 行

转载 作者:太空宇宙 更新时间:2023-11-04 02:52:11 26 4
gpt4 key购买 nike

我有一个看起来像这样的文件:

~~~~~~~~~~~~~~~~~~~~~
Start
2, 0.001, 1.0
alpha = 0.001
beta = 1.3

...
...
...

new evaluation
complete
print out alpha & beta
alpha = 0.19
beta = 1.41
End

~~~~~~~~~~~~~~~~~~~~~
Start
....

我想提取“Start”后的三行和“print out”后的两行。基本上,它应该是:

~~~~~~~~~~~~~~~~~~~~~
2, 0.001, 1.0
alpha = 0.001
beta = 1.3

alpha = 0.19
beta = 1.41

~~~~~~~~~~~~~~~~~~~~~

这是我用的:

summary = open("summary_accuracy.txt","w")
content = []
with open(filename,'r') as f:
for line in f:
if "Start" in line:
content += [f.readline() for i in range(3)]
if "print out" in line:
content += [f.readline() for i in range(2)]
content += "~~~~~~~~~~"

summary.write(content)

但是,我得到了错误:

content += [f.readline() for i in range(3)]
ValueError: Mixing iteration and read methods would lose data

最佳答案

尝试使用 next(f) 而不是 f.readline()

也可以考虑使用 regular expressions对于这个任务:

>>> import re
>>> re.search(r'^Start\s(.*\s.*\s.*\s)', s, re.MULTILINE).group(1)
'2, 0.001, 1.0\nalpha = 0.001\nbeta = 1.3\n'
>>> re.search(r'^print out.*\s(.*\s.*\s)', s, re.MULTILINE).group(1)
'alpha = 0.19\nbeta = 1.41\n'

关于Python 在文件中的模式之后迭代 grep 行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43532596/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com