![](/img/trans.png)
[英]How to lookup string in text file and output specific lines above and below
[英]How to search for a combination of keywords in a text-file, extract lines above and below, and then export to Excel using pandas
我试图在几个SEC 10-K文件中的特定关键字组合之前和之后提取5行,然后将这些数据导出到Excel中,以便我可以进一步手动处理它。 不幸的是,我必须依赖.txt格式的文件而不是.html或.xblr文件,因为后者并不总是可用。 我已经下载并部分清理.txt文件以删除不需要的标签。
简而言之,我的目标是告诉python循环下载的.txt文件(例如,所有那些在同一文件夹中或仅通过提供带有所有文件名的引用.txt列表),打开每个文件,查找单词“累积效应”(理想情况下与其他关键字结合使用,请参见下面的代码),在其前后提取5行,然后将输出导出到excel,其中A列中的文件名和B列中的提取段落。
使用此代码,我设法在一个.txt文件的关键字“累积效应”之上和之下提取5行(您可以在此处找到,以供参考)。 但是,我仍然在努力自动化/循环整个过程并使用pandas将提取的文本导出到Excel。
import collections
import itertools
import sys
from pandas import DataFrame
filing='0000950123-94-002010_1.txt'
#with open(filing, 'r') as f:
with open(filing, 'r', encoding='utf-8', errors='replace') as f:
before = collections.deque(maxlen=5)
for line in f:
if ('cumulative effect' in line or 'Cumulative effect' in line) and ('accounting change' in line or 'adoption' in line or 'adopted' in line or 'charge' in line):
sys.stdout.writelines(before)
sys.stdout.write(line)
sys.stdout.writelines(itertools.islice(f, 5))
break
before.append(line)
findings = {'Filing': [filing],
'Extracted_paragraph': [line]
}
df = DataFrame(findings, columns= ['Filing', 'Extracted_paragraph'])
export_excel = df.to_excel (r'/Users/myname/PYTHON/output.xlsx', index = None, header=True)
print (df)
使用这行代码我获得了我需要的段落,但我只设法将包含关键字的单行导出到excel而不是整个文本。 这是python输出 , 这是导出到Excel的文本 。
如何创建循环并将整个感兴趣的段落正确导出到excel中? 非常感谢提前!!
我相信你的基本错误在于
'Extracted_paragraph': [line]
应该是的
'Extracted_paragraph': [before]
因此,通过一些简化的更改,代码的主要部分应如下所示:
with open(filing, 'r', encoding='utf-8', errors='replace') as f:
before = collections.deque(maxlen=5)
for line in f:
if ('cumulative effect' in line or 'Cumulative effect' in line) and ('accounting change' in line or 'adoption' in line or 'adopted' in line or 'charge' in line):
break
before.append(line)
before = ''.join(before)
findings = {'Filing': [filing],
'Extracted_paragraph': [before]
}
df = DataFrame(findings, columns= ['Filing', 'Extracted_paragraph'])
然后从那里继续导出到Excel等。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.