如何使用python查找连续行

如何使用python查找连续行,python,Python,我有一个文件,如下所示: the 1 file is: none the 2 file is: a-h-f the 3 file is: a-h-p the 4 file is: none 我想用python知道哪两个连续的文件是相互竞争的,而不是没有。以这个文件为例,“2文件”和“3文件”是连续的,并且有内容。我期望的结果是: the 2 file is: a-h-f the 3 file is: a-h-p 请有人给我一些提示。谢谢。将您的行放入列表中,即可以是l

我有一个文件,如下所示:

the 1 file is:
none
the 2 file is:
a-h-f
the 3 file is:
a-h-p
the 4 file is:
none
我想用python知道哪两个连续的文件是相互竞争的,而不是没有。以这个文件为例,“2文件”和“3文件”是连续的,并且有内容。我期望的结果是:

   the 2 file is:
   a-h-f
   the 3 file is:
   a-h-p

请有人给我一些提示。谢谢。

将您的行放入列表中,即可以是
lines=f.readlines()
,其中
f
是文件对象,或者:

lines = '''the 1 file is:
none
the 2 file is:
a-h-f
the 3 file is:
a-h-p
the 4 file is:
none
'''.splitlines()
然后:

印刷品:

the 2 file is:
a-h-f
the 3 file is:
a-h-p

列出4个连续的元素,并过滤其中没有的元素。然后派对

with open("input_file","r") as in_file:
    lines = in_file.read().split("\n")
consecutive_lines_4 = [lines[i:i+4] for i in range(0,len(lines)-3),2]
result = [i for i in consecutive_lines_4 if 'none' not in i]
print(result)

为什么不直接使用
grep-a1'呢[23]文件是:'…
?为什么要使用Python呢?就这点而言,如果您将文件名和内容放在一行,它更适合于
grep
。您可以轻松地将文件重新格式化为该格式。一次迭代文件两行。一种方法可以是一次生成两行的函数。然后检查None值并丢弃一些行就很简单了。要一次迭代两行,请查看函数
iter
next
StopIteration
异常。@hruyu请查看我的答案
with open("input_file","r") as in_file:
    lines = in_file.read().split("\n")
consecutive_lines_4 = [lines[i:i+4] for i in range(0,len(lines)-3),2]
result = [i for i in consecutive_lines_4 if 'none' not in i]
print(result)