擅长:python、mysql、java
<p>您编写的代码几乎没有问题,其中一个问题是在扫描文档查找“结束文本”时,您没有保存所需的部分文本。如果可能的话,最好在内存中存储尽可能少的文本,因为我们不知道您试图分析的文档有多大。为此,我们可以在读取原始文件时写入新文件</p>
<p>Ronie的答案是正确的,但它没有说明您只想在第二次出现“开始提示”后才开始保存文本。不幸的是,我还不能评论建议的编辑,所以我添加它作为一个新的答案。
试试这个:</p>
<pre><code>for file in tqdm(files):
with open(file, encoding='ISO-8859-1') as f, open(os.path.join('QTR4_Risk_Factors', os.path.basename(file)) , 'w') as w:
start_hint_counter = 0
write = False
for line in f:
if write is False and line.strip() == 'Item 1A.Risk Factors':
start_hint_counter += 1
if start_hint_counter == 2:
write = True
if write is True:
if line.strip() == 'Item 1B':
break
else:
w.write(line)
</code></pre>