擅长:python、mysql、java
<p>我编写了一个小函数,可能对您的案例有用:</p>
<pre><code>from collections import deque
def search_cont(filename, search_for, num_before, num_after):
with open(filename) as f:
before_lines = deque(maxlen=num_before)
after_lines = deque(maxlen=num_after+1)
for _ in range(num_after+1):
after_lines.append(next(f))
while len(after_lines)>0:
current_line = after_lines.popleft()
if search_for in current_line:
print("".join(before_lines))
print(current_line)
print("".join(after_lines))
print(" -")
before_lines.append(current_line)
try:
after_lines.append(next(f))
except StopIteration:
pass
</code></pre>
<p>你把它叫做</p>
<pre><code>search_for = raw_input('enter the word:')
search_cont('mytext.txt', search_for, 3, 3)
</code></pre>
<p>这个解决方案没有文件大小的上限(除非你有很长的行),因为内存中永远不会超过7行</p>