gpt4 book ai didi

python - 如何从文件中打印最后两个匹配的字符串

转载 作者:太空宇宙 更新时间:2023-11-04 11:14:10 24 4
gpt4 key购买 nike

我需要打印文件的最后两行,它们与“sample”或“another”相匹配。目前我正在使用以下代码,它按要求工作。但我需要知道是否有任何方法可以进一步缩短它。

LOG_FILE = "foo"
for line in reversed(open(LOG_FILE).readlines()):
if 'sample' in line:
print(line.rstrip())
break;

for line in reversed(open(LOG_FILE).readlines()):
if 'another' in line:
print(line.rstrip())
break;

期望的输出:

python  sample_prog.py
5 this is also INTERESTING sample line
3 this is another line

输入文件:

cat foo
1 this is a line
2 this is a another line
3 this is another line
4 and this is INTERESTING sample line
5 this is also INTERESTING sample line

注意:可以安全地假设“sample”和“another”永远不会在同一行。

最佳答案

从预定义列表中使用模式(如果输入文件不是很大而无法反转):

LOG_FILE="foo.txt"

with open(LOG_FILE) as f:
patterns = ['sample', 'another']

for line in reversed(f.readlines()):
if not patterns: # all patterns were consumed
break
for pat in patterns[:]:
if pat in line:
print(line.strip())
patterns.remove(pat)
break

输出:

5 this is also INTRESTING sample line
3 this is another line

关于python - 如何从文件中打印最后两个匹配的字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57416411/

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