python - 如何使用 Pypdf2 从 Pdf 中提取文本,不包括图表和表格中的文本内容
问题描述
我想从 python 中的 PPT 和 PDF 文件中提取文本内容。
虽然使用 PPTX 可以很好地提取文本,但在使用我不想要的 extract_text() 时,使用 PyPDF2 从图表和表格以及 PDF 中提取文本内容。
我尝试了不同的方法,但无法找到实现这一目标的方法。有什么办法可以做到这一点?Pfb 的代码相同。
import ntpath
import os
import glob
import PyPDF2
import pandas as pd from pptx import Presentation
df_header=pd.DataFrame(columns=['Document_Name', 'Document_Type', 'Page_No', 'Text', 'Report Name'])
df_header.to_csv('Downloads\\\\FinalSample.csv', mode='a', header=True)
for eachfile in glob.glob("D:\\CP US People-Centric Hub (19-SCP-3063)\\Reports\\/*\\\\/*"):
file1 = eachfile.split("\\")
report_name = file1[3]
if eachfile.endswith(".pptx"):
data=[]
prs = Presentation(eachfile)
for slide in prs.slides:
text_runs = ''
slide_num = prs.slides.index(slide) + 1
for shape in slide.shapes:
if not shape.has_text_frame:
continue
for paragraph in shape.text_frame.paragraphs:
text_runs = text_runs + ' ' + paragraph.text
data.append([ntpath.basename(eachfile), 'PPT', slide_num, text_runs,report_name])
df_ppt=pd.DataFrame(data)
df_ppt.to_csv('Downloads\\\\FinalSample.csv', mode='a', header=False)
elif eachfile.endswith(".pdf"):
data1=[]
pdfFileObj = open(eachfile, 'rb')
pdfReader = PyPDF2.PdfFileReader(pdfFileObj)
outlines = pdfReader.getOutlines()
for pageNum in range(pdfReader.numPages):
data1.append([ntpath.basename(eachfile), 'PDF', pageNum + 1,pdfReader.getPage(pageNum).extractText(),report_name])
df_pdf=pd.DataFrame(data1)
df_pdf.to_csv('Downloads\\\\FinalSample.csv', mode='a', header=False)
pdfFileObj.close()
解决方案
不,抱歉:从 PDF 中仅提取正文并省略图形标题、脚注、页眉、页脚、页码等通常是不可能的。这是因为“正文”在 PDF 格式中并不是真正定义的概念。
但是,您可以深入研究库并添加一些针对图形标题的启发式方法,例如丢弃没有文本的大间隙的文本块,或者太短(但是标题呢?),或者字体大小比均值。
推荐阅读
- python - 轮播滑动方向的 Kivy RecycleView 不起作用
- reactjs - 有没有办法在 react-admin 的 ReferenceArrayInput -> SelectArrayInput 组件中显示预先选择的项目?
- node.js - 重新加载时反应Nodejs页面空白
- ios - 当环境对象更新导致同一视图重新加载时,如何导航到另一个 SwiftUI 视图
- tkinter - 显示图像 tkinter 的问题
- typescript - 如何在泛型函数上使用正确的类型函数?
- pdfbox - Text displayed in blue although PDAnnotation removed
- r - Stack(),模型的 blending_predictions,导致警告:需要相关性计算,但估计值是恒定的,标准差为 0
- android - 如何在android中的所有活动之上显示自定义警报?
- java - 使用 Java stream() API 过滤掉没有 List 的单个元素