擅长:python、mysql、java
<p>这也许不是最好的解决方案,但您可以使用deque在目标线上方捕捉n条线:</p>
<pre><code>from collections import deque
from itertools import takewhile
test = """
real others
address xxx.xxx.xxx
real local
address 127.0.0.1
real others
address xxx.xxx.xxx
""".split("\n")
pattern = "address 127.0.0.1"
print deque(takewhile(lambda x:x.strip()!=pattern, test), 2)[0]
</code></pre>
<p>将测试变量更改为file(“yourfilename”)以从文本文件中读取行。在</p>