擅长:python、mysql、java
<p>这可以使用<code>yield</code>来完成</p>
<p>假设您有一个如下所示的文件<code>sample.txt</code>,并且您关心以<code>keyword</code>开头的行:</p>
<pre><code>not what you're looking for
keyword huzzah
balh balh
blah blah
other text
other lines
keyword found it
keyword hey another one
not me
forget it
keyword yes
nope
</code></pre>
<p>以下代码将执行您想要的操作:</p>
^{pr2}$
<p>这就产生了:</p>
<pre><code>['keyword huzzah\n', 'keyword found it\n', 'keyword hey another one\n', 'keyword yes\n']
</code></pre>