擅长:python、mysql、java
<p>使用状态机。这意味着,一旦你看到你的开场白,就要设置一个状态,这样你就知道下面几行与你有关了。然后继续寻找结束模式来关闭它:</p>
<pre><code>def printlines():
# this is our state
isWithin = False
with open('text.txt') as f:
for line in f:
# Since the line contains the line breaking character,
# we have to remove that first
line = line.rstrip()
# check for the patterns to change the state
if line == "***a":
isWithin = True
elif line == " -a":
isWithin = False
# check whether we’re within our state
elif isWithin:
print line
</code></pre>
<p>因为我们只在<code>isWithin</code>状态下打印,所以我们可以很容易地跳过<code>***a</code>/<code> -a</code>模式之外的任何部分。因此,处理以下文件将正确地输出<code>Hello</code>和{<cd5>}而不输出其他内容:</p>
^{pr2}$
<p>另外,您应该使用<code>with</code>语句打开文件,并直接迭代file对象,而不是读取它并调用<code>splitlines()</code>。这样可以确保文件被正确地关闭,并且只读取一行又一行的内容,从而提高内存效率。在</p>