我认为正则表达式应该可以工作。但是,在这里我想也许这可能是一个展示使用the walrus operator := in python 3.8: 在列表理解中查找多行模式位置的示例的机会。
如果模式更复杂,将来可能会有用。
text = """
text
text
text
to remove
text
text
text
to remove
text
text
text
"""
curr = ("", "", "", "")
positions = [
(i-4, i)
for i, line in enumerate(text.split("\n"))
if (curr := (curr[1], curr[2], curr[3], line.strip())) == ("", "", "to remove", "")
]
结果positions 这里是一个元组列表,指示分隔符模式的范围:
[(3, 7), (10, 14)]
是的,已经太复杂了!最后一点,请耐心等待。您可以将范围列表用作any() 的过滤器,以检查行是否不在任何分隔符范围内:
remained_lines = [
line
for pos, line in enumerate(text.split("\n"))
if not any([i<= pos < j for i, j in positions])
]
new_text = "\n".join(remained_lines)
总之,尽可能使用正则表达式,但是,这里我有一些新的和旧的 Python 特性,对于未来遇到更奇怪分隔符情况的读者可能会派上用场。