内容简介:版权声明:本文为博主原创文章,未经博主允许不得转载。 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文件》,希望对大家有所帮助,如果大家有任何疑问请给我留言,小编会及时回复大家的。在此也非常感谢大家对 码农网 的支持!
猜你喜欢:- mybatis源码配置文件解析之三:解析typeAliases标签
- 安卓 so 文件解析详解
- perl解析pcap文件
- Nginx 源码:配置文件解析
- 要解析一个配置文件,当打开文件的时候我崩溃了
- Django源码解析|Migrations文件的生成
本站部分资源来源于网络,本站转载出于传递更多信息之目的,版权归原作者或者来源机构所有,如转载稿涉及版权问题,请联系我们。
Machine Learning
Kevin Murphy / The MIT Press / 2012-9-18 / USD 90.00
Today's Web-enabled deluge of electronic data calls for automated methods of data analysis. Machine learning provides these, developing methods that can automatically detect patterns in data and then ......一起来看看 《Machine Learning》 这本书的介绍吧!
在线进制转换器
各进制数互转换器
html转js在线工具
html转js在线工具