使用pdfminer解析pdf文件

栏目: Python · 发布时间: 6年前

内容简介:版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/kongxx/article/details/85107847

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/kongxx/article/details/85107847

最近要做个从 pdf 文件中抽取文本内容的工具,大概查了一下 python 里可以使用 pdfminer 来实现。下面就看看怎样使用吧。

python的工具,安装当然是使用pip安装了。

pip install pdfminer

命令行方式

为了使用方便,pdfminer 提供了一个命令行 工具 来直接转换pdf文件,使用方法如下:

pdf2txt.py <path_to_pdf_file>

编程方式

除了命令行方式以外,对于复杂应用场景,pdfminer 也提供了以编程方式来转换 pdf 文件,主要使用下面几个类来实现:

  • PDFParser: 用来解析pdf文件。
  • PDFDocument:用来保存 PDFParser 解析后的对象。
  • PDFPageInterpreter:用来处理解析后的文档页面内容。
  • PDFResourceManager:pdf 共享资源管理器,用于存储共享资源,如字体或图像。

下面看一个例子:

#!/usr/bin/env python
# -*- coding: utf-8 -*-
from pdfminer.pdfparser import PDFParser
from pdfminer.pdfdocument import PDFDocument
from pdfminer.pdfpage import PDFPage, PDFTextExtractionNotAllowed
from pdfminer.pdfinterp import PDFResourceManager, PDFPageInterpreter
from pdfminer.converter import PDFPageAggregator
from pdfminer.layout import LAParams
import StringIO


class PDFUtils():

    def __init__(self):
        pass

    def pdf2txt(self, path):
        output = StringIO.StringIO()
        with open(path, 'rb') as f:
            praser = PDFParser(f)

            doc = PDFDocument(praser)

            if not doc.is_extractable:
                raise PDFTextExtractionNotAllowed

            pdfrm = PDFResourceManager()

            laparams = LAParams()

            device = PDFPageAggregator(pdfrm, laparams=laparams)

            interpreter = PDFPageInterpreter(pdfrm, device)

            for page in PDFPage.create_pages(doc):
                interpreter.process_page(page)
                layout = device.get_result()
                for x in layout:
                    if hasattr(x, "get_text"):
                        content = x.get_text()
                        output.write(content)

        content = output.getvalue()
        output.close()
        return content


if __name__ == '__main__':
    path = u'/tmp/abc.pdf'
    pdf_utils = PDFUtils()
    print pdf_utils.pdf2txt(path)

以上所述就是小编给大家介绍的《使用pdfminer解析pdf文件》,希望对大家有所帮助,如果大家有任何疑问请给我留言,小编会及时回复大家的。在此也非常感谢大家对 码农网 的支持!

查看所有标签

猜你喜欢:

本站部分资源来源于网络,本站转载出于传递更多信息之目的,版权归原作者或者来源机构所有,如转载稿涉及版权问题,请联系我们

TensorFlow:实战Google深度学习框架(第2版)

TensorFlow:实战Google深度学习框架(第2版)

顾思宇、梁博文、郑泽宇 / 电子工业出版社 / 2018-2-1 / 89

TensorFlow是谷歌2015年开源的主流深度学习框架,目前已得到广泛应用。《TensorFlow:实战Google深度学习框架(第2版)》为TensorFlow入门参考书,旨在帮助读者以快速、有效的方式上手TensorFlow和深度学习。书中省略了烦琐的数学模型推导,从实际应用问题出发,通过具体的TensorFlow示例介绍如何使用深度学习解决实际问题。书中包含深度学习的入门知识和大量实践经......一起来看看 《TensorFlow:实战Google深度学习框架(第2版)》 这本书的介绍吧!

Base64 编码/解码
Base64 编码/解码

Base64 编码/解码

XML 在线格式化
XML 在线格式化

在线 XML 格式化压缩工具

html转js在线工具
html转js在线工具

html转js在线工具