首页 > 解决方案 > 如何使用 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()

标签: pythontextpypdf2

解决方案


不,抱歉:从 PDF 中提取正文并省略图形标题、脚注、页眉、页脚、页码等通常是不可能的。这是因为“正文”在 PDF 格式中并不是真正定义的概念。

但是,您可以深入研究库并添加一些针对图形标题的启发式方法,例如丢弃没有文本的大间隙的文本块,或者太短(但是标题呢?),或者字体大小比均值。


推荐阅读