[英]How to extract the part of a text file after the second occurrence of a specific word using Python
我试图在第二次出现特定单词之后提取文本文件的一部分,直到再次出现另一个特定单词为止。 原因是在目录中首先说明了这两个词。 因此,当我运行代码时,我得到了第一次出现的 0 output。
示例文本:
目录
项目 1a. 风险因素
项目 1b
目录结束
主要内容
第 1a 项。 风险因素
项目 1b
我需要在第 1a 项的第二次出现之间提取文本。 风险因素和第 1b 项的第二次出现。
我的代码如下:
for file in tqdm(files):
with open(file, encoding='ISO-8859-1') as f:
for line in f:
if line.strip() == 'Item 1A.Risk Factors':
break
for line in f:
if line.strip() == 'Item 1B':
break
f=open(os.path.join('QTR4_Risk_Factors',
os.path.basename(file)) , 'w')
f.write(line)
f.close()
我认为您应该制作一个标志以知道何时复制这些行。 您还可以在上下文管理器中同时打开 2 个或更多文件。
with open(file, encoding='ISO-8859-1') as f, open(os.path.join('QTR4_Risk_Factors', os.path.basename(file)) , 'w') as w:
write = False
for line in f:
if line.strip() == 'Item 1A.Risk Factors':
write = True
continue
elif line.strip() == 'Item 1B':
write = False
if write == True:
w.write(line)
Ronie 的回答是朝着正确的方向发展,但它没有解决您只想在第二次出现“开始提示”后才开始保存文本的事实。
编辑:添加continue
您编写的代码几乎没有问题,其中一个问题是您在扫描文档以查找“结束文本”时没有保存所需的文本部分。 如果可能的话,最好在 memory 中存储尽可能少的文本,因为我们不知道您要分析的文档有多大。 为此,我们可以在读取原始文件的同时写入新文件。
Ronie 的回答是朝着正确的方向发展,但它没有解决您只想在第二次出现“开始提示”后才开始保存文本的事实。 不幸的是,我还不能评论建议编辑,所以我将其添加为新答案。 尝试这个:
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)
你可以试试正则表达式:
import re
t = """Item 1a.Risk Factors
not any text (unwanted portion)
Item 1b
End of table of contents
Main content
Item 1a. Risk Factors
text (wanted portion)
text (wanted portion)
text (wanted portion)
Item 1b"""
crit = re.compile('Item 1a.Risk Factors.*?Item 1a. Risk Factors(.*?)Item 1b', re.I|re.DOTALL)
if re.search(crit, t):
result = re.search(crit, t).group(1)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.