擅长:python、mysql、java
<p>您可能会发现使用<a href="http://docs.python.org/library/itertools.html#itertools.groupby" rel="nofollow noreferrer">itertools.groupby</a>解决这个问题更容易。</p>
<pre><code>def get_text_blocks(filename):
import itertools
with open(filename,'r') as f:
groups = itertools.groupby(f, lambda line:line.startswith('-- -'))
return [''.join(lines) for is_separator, lines in groups if not is_separator]
</code></pre>
<p>另一种方法是使用<a href="http://www.amk.ca/python/howto/regex/" rel="nofollow noreferrer">regular expression</a>来匹配分隔符:</p>
<pre><code>def get_text_blocks(filename):
import re
seperator = re.compile('^-- -.*', re.M)
with open(filename,'r') as f:
return re.split(seperator, f.read())
</code></pre>