【问题标题】:Remove header and footer from pdftotext module in Python从 Python 中的 pdftotext 模块中删除页眉和页脚
【发布时间】:2021-05-13 08:35:51
【问题描述】:

我正在使用pdftotext python 包从 pdf 中提取文本,但是我需要从文本文件中删除页眉和页脚以仅提取内容。

有两种方法可以解决这个问题:

  1. 在文本文件中使用正则表达式
  2. 在从 pdf 中获取文本时使用一些过滤器

现在,当前的问题是页眉和页脚与页面不一致。

例如,标题的前 1-2 行可能有承包商的地址,这是一致的,但标题的第 3 行有节和页面所遵循的主题。类似地,页脚由项目编号(也不是固定数值)、小节编号和一些设计词组成,后跟一个应该一致的日期(但每个项目都不同)。还应该注意的是,每个项目的 pdf 文件可以是 500 多页,但可能会根据部分进行拆分。

目前我正在使用此代码来提取信息。有什么参数我不知道可以用来去除页眉和页脚吗?

import pdftotext

def get_data(pdf_path):

    with open(pdf_path, "rb") as f:
        pdf = pdftotext.PDF(f)

    print("Pages : ",len(pdf))

    with open('text-pdftotext.txt', 'w') as k:
        k.write("\n\n".join(pdf))

    f.close()
    k.close()

get_data('specification_file.pdf')

【问题讨论】:

    标签: python ocr text-extraction pdftotext


    【解决方案1】:

    您的问题的一个答案是使用pdf2image 模块将PDF 视为图像,并使用pytesseract 提取其中的文本。这样,您就可以使用opencv 裁剪页眉和页脚,以仅保留文件的核心。但是它可能不是完美的方法,因为 pdf2image 方法 convert_from_path 可能需要很长时间才能运行。

    如果你有兴趣,我在这里放一些代码。

    首先确保您安装了所有必要的依赖项以及 Tesseract 和 ImageMagik。您可以在网站上找到有关安装的任何信息。如果您正在使用 Windows,那么有一篇很好的 Medium 文章 here

    使用 pdf2image 将 PDF 转换为图像:

    如果您在 Windows 上工作,请不要忘记添加您的 poppler 路径。它应该看起来像 r'C:\<your_path>\poppler-21.02.0\Library\bin'

    def pdftoimg(fic,output_folder, poppler_path):
        # Store all the pages of the PDF in a variable 
        pages = convert_from_path(fic, dpi=500,output_folder=output_folder,thread_count=9, poppler_path=poppler_path) 
    
        image_counter = 0
    
        # Iterate through all the pages stored above 
        for page in pages: 
            filename = "page_"+str(image_counter)+".jpg"
            page.save(output_folder+filename, 'JPEG') 
            image_counter = image_counter + 1
            
        for i in os.listdir(output_folder):
            if i.endswith('.ppm'):
                os.remove(output_folder+i)
    

    裁剪图像页脚和页眉:

    我不知道您的页脚和页眉的大小,但通过尝试多次裁剪您的图像,您应该能够找到要使用的正确尺寸。 然后,您可以使用 OpenCV 裁剪方法 new_head 是标题下方 y 轴上顶部像素的值,new_bottom 是底部像素来裁剪图像以保留 PDF 的正文在页脚开始的 y 轴上。

    def crop_img(fic, output_folder):
        img = cv2.imread(fic)
        shape = img.shape
        crop_img = img[new_head:new_bottom, 0:shape[1]]
        cv2.imwrite(output_folder+name, crop_img)
    

    从图像中提取文本:

    您的 tesseract 路径将是这样的:r'C:\Program Files\Tesseract-OCR\tesseract.exe'

    def imgtotext(img, tesseract_path):
        # Recognize the text as string in image using pytesserct 
        pytesseract.pytesseract.tesseract_cmd = tesseract_path
        text = str(((pytesseract.image_to_string(Image.open(img))))) 
        text = text.replace('-\n', '')
        
        return text
    

    【讨论】:

    • 感谢您的努力,但正如我所说,这是一个 500 多页的 pdf,将它们全部转换为图像不是一个好主意(更不用说 pdftotext 能够达到的准确性)文本提取)。
    猜你喜欢
    • 2012-01-03
    • 2015-10-01
    • 2015-11-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-09-18
    相关资源
    最近更新 更多