#自动读取文件夹内的各基金报告pdf,提取里面的运行报告,并汇总保存到word表格
from pathlib import Path
import pdfplumber
import pandas as pd
import docx
import os
p = Path("E:/基金报告爬取/") #读取路劲
FileList = list(p.glob("*.pdf"))
#print(FileList)
count = 0
for fp in FileList:
#print(fp)
with pdfplumber.open(fp) as pdf:
content = ''
#len(pdf.pages)为PDF文档页数
for i in range(len(pdf.pages)):
#pdf.pages[i] 是读取PDF文档第i+1页
page = pdf.pages[i]
#page.extract_text()函数即读取文本内容,下面这步是去掉文档最下面的页码
page_content = '\n'.join(page.extract_text().split('\n')[:-1])
content = content + page_content
#切片内容
name = os.path.split(os.path.splitext(fp)[0])[1]#截取fp路径的无后缀路径,在截取文件路径中的文件名
strategy = content.split('投资策略和运作分析')[1].split('报告期内基金的业绩表现')[0]
strategy = strategy.replace('\n','')#去掉内容内的换行符,因为word会自动换行
#打开docx
doc = docx.Document(r'E:\基金报告爬取\基金季度报告.docx')
table = doc.add_table(rows=1, cols=2)
title_cells = table.rows[0].cells
title_cells[0].text =name
title_cells[1].text =strategy
doc.save(r'E:\基金报告爬取\基金季度报告.docx')
count+=1
print("\r当前进度: {:.2f}%".format(count*100/len(FileList)),end="")
功能:
已经下载完毕的基金季报或年报,自动截取其中的运行报告,存储到word中
优化了工作进程%比打印出来
涉及到的语言知识点:
- pathlib库获取文件夹下所有文件路径
- pdfplumber库读取pdf文件和编辑功能
- os获取pdf文件名功能
- docx库写入表格功能
目前缺点:
word文件必须一开始就有,如果是第一次运行,没有文件,程序会报错