详解python使用pdfminer解析pdf实例

本篇文章主要介绍了python使用pdfminer解析pdf代码实例,小编觉得挺不错的,现在分享给大家,也给大家做个参考。一起跟随小编过来看看吧

近期在做爬虫时有时会遇到网站只提供pdf的情况,这样就不能使用scrapy直接抓取页面内容了,只能通过解析pdf的方式处理,目前的解决方案大致只有pypdf和pdfminer。因为据说pdfminer更适合文本的解析,而我需要解析的正是文本,因此最后选择使用pdfminer(这也就意味着我对pypdf一无所知了)。

首先说明的是解析pdf是非常蛋疼的事,即使是pdfminer对于格式不工整的pdf解析效果也不怎么样,所以连pdfminer的开发者都吐槽pdf is evil. 不过这些并不重要。

一.安装:

1.首先下载源文件包 pypi.python.org/pypi/pdfminer/,解压,然后命令行安装即可:python setup.py install

2.安装完成后使用该命令行测试:pdf2txt.py samples/simple1.pdf,如果显示以下内容则表示安装成功:

hello world hello world h e l l o w o r l d h e l l o w o r l d

3.如果要使用中日韩文字则需要先编译再安装: 

# make cmap
python tools/conv_cmap.py pdfminer/cmap adobe-cns1 cmaprsrc/cid2code_adobe_cns1.txtreading ‘cmaprsrc/cid2code_adobe_cns1.txt’…writing ‘cns1_h.py’……(this may take several minutes)
# python setup.py install

二.使用

由于解析pdf是一件非常耗时和内存的工作,因此pdfminer使用了一种称作lazy parsing的策略,只在需要的时候才去解析,以减少时间和内存的使用。要解析pdf至少需要两个类:pdfparser 和 pdfdocument,pdfparser 从文件中提取数据,pdfdocument保存数据。另外还需要pdfpageinterpreter去处理页面内容,pdfdevice将其转换为我们所需要的。pdfresourcemanager用于保存共享内容例如字体或图片。

官方文档给了几个demo但是都过于简略,虽然给了一个详细一些的demo,但链接地址是旧的现在已经失效,不过最终还是找到了新的地址:denis.papathanasiou.org/posts/2010.08.04.post.html

这个demo就比较详细了,源码如下:

#!/usr/bin/python
import sys
import os
from binascii import b2a_hex
###
### pdf-miner requirements
###
from pdfminer.pdfparser import pdfparser
from pdfminer.pdfdocument import pdfdocument, pdfnooutlines
from pdfminer.pdfpage import pdfpage
from pdfminer.pdfinterp import pdfresourcemanager, pdfpageinterpreter
from pdfminer.converter import pdfpageaggregator
from pdfminer.layout import laparams, lttextbox, lttextline, ltfigure, ltimage, ltchar
def with_pdf (pdf_doc, fn, pdf_pwd, *args):
“””open the pdf document, and apply the function, returning the results”””
result = none
try:
# open the pdf file
fp = open(pdf_doc, ‘rb’)
# create a parser object associated with the file object
parser = pdfparser(fp)
# create a pdfdocument object that stores the document structure
doc = pdfdocument(parser, pdf_pwd)
# connect the parser and document objects
parser.set_document(doc)
# supply the password for initialization
if doc.is_extractable:
# apply the function and return the result
result = fn(doc, *args)
# close the pdf file
fp.close()
except ioerror:
# the file doesn’t exist or similar problem
pass
return result
###
### table of contents
###
def _parse_toc (doc):
“””with an open pdfdocument object, get the table of contents (toc) data
[this is a higher-order function to be passed to with_pdf()]”””
toc = []
try:
outlines = doc.get_outlines()
for (level,title,dest,a,se) in outlines:
toc.append( (level, title) )
except pdfnooutlines:
pass
return toc
def get_toc (pdf_doc, pdf_pwd=”):
“””return the table of contents (toc), if any, for this pdf file”””
return with_pdf(pdf_doc, _parse_toc, pdf_pwd)
###
### extracting images
###
def write_file (folder, filename, filedata, flags=’w’):
“””write the file data to the folder and filename combination
(flags: ‘w’ for write text, ‘wb’ for write binary, use ‘a’ instead of ‘w’ for append)”””
result = false
if os.path.isdir(folder):
try:
file_obj = open(os.path.join(folder, filename), flags)
file_obj.write(filedata)
file_obj.close()
result = true
except ioerror:
pass
return result
def determine_image_type (stream_first_4_bytes):
“””find out the image file type based on the magic number comparison of the first 4 (or 2) bytes”””
file_type = none
bytes_as_hex = b2a_hex(stream_first_4_bytes)
if bytes_as_hex.startswith(‘ffd8’):
file_type = ‘.jpeg’
elif bytes_as_hex == ‘89504e47’:
file_type = ‘.png’
elif bytes_as_hex == ‘47494638’:
file_type = ‘.gif’
elif bytes_as_hex.startswith(‘424d’):
file_type = ‘.bmp’
return file_type
def save_image (lt_image, page_number, images_folder):
“””try to save the image data from this ltimage object, and return the file name, if successful”””
result = none
if lt_image.stream:
file_stream = lt_image.stream.get_rawdata()
if file_stream:
file_ext = determine_image_type(file_stream[0:4])
if file_ext:
file_name = ”.join([str(page_number), ‘_’, lt_image.name, file_ext])
if write_file(images_folder, file_name, file_stream, flags=’wb’):
result = file_name
return result
###
### extracting text
###
def to_bytestring (s, enc=’utf-8′):
“””convert the given unicode string to a bytestring, using the standard encoding,
unless it’s already a bytestring”””
if s:
if isinstance(s, str):
return s
else:
return s.encode(enc)
def update_page_text_hash (h, lt_obj, pct=0.2):
“””use the bbox x0,x1 values within pct% to produce lists of associated text within the hash”””
x0 = lt_obj.bbox[0]
x1 = lt_obj.bbox[2]
key_found = false
for k, v in h.items():
hash_x0 = k[0]
if x0 >= (hash_x0 * (1.0-pct)) and (hash_x0 * (1.0+pct)) >= x0:
hash_x1 = k[1]
if x1 >= (hash_x1 * (1.0-pct)) and (hash_x1 * (1.0+pct)) >= x1:
# the text inside this lt* object was positioned at the same
# width as a prior series of text, so it belongs together
key_found = true
v.append(to_bytestring(lt_obj.get_text()))
h[k] = v
if not key_found:
# the text, based on width, is a new series,
# so it gets its own series (entry in the hash)
h[(x0,x1)] = [to_bytestring(lt_obj.get_text())]
return h
def parse_lt_objs (lt_objs, page_number, images_folder, text=[]):
“””iterate through the list of lt* objects and capture the text or image data contained in each”””
text_content = []
page_text = {} # k=(x0, x1) of the bbox, v=list of text strings within that bbox width (physical column)
for lt_obj in lt_objs:
if isinstance(lt_obj, lttextbox) or isinstance(lt_obj, lttextline):
# text, so arrange is logically based on its column width
page_text = update_page_text_hash(page_text, lt_obj)
elif isinstance(lt_obj, ltimage):
# an image, so save it to the designated folder, and note its place in the text
saved_file = save_image(lt_obj, page_number, images_folder)
if saved_file:
# use html style tag to mark the position of the image within the text
text_content.append(‘‘)
else:
print >> sys.stderr, “error saving image on page”, page_number, lt_obj.__repr__
elif isinstance(lt_obj, ltfigure):
# ltfigure objects are containers for other lt* objects, so recurse through the children
text_content.append(parse_lt_objs(lt_obj, page_number, images_folder, text_content))
for k, v in sorted([(key,value) for (key,value) in page_text.items()]):
# sort the page_text hash by the keys (x0,x1 values of the bbox),
# which produces a top-down, left-to-right sequence of related columns
text_content.append(”.join(v))
return ‘\n’.join(text_content)
###
### processing pages
###
def _parse_pages (doc, images_folder):
“””with an open pdfdocument object, get the pages and parse each one
[this is a higher-order function to be passed to with_pdf()]”””
rsrcmgr = pdfresourcemanager()
laparams = laparams()
device = pdfpageaggregator(rsrcmgr, laparams=laparams)
interpreter = pdfpageinterpreter(rsrcmgr, device)
text_content = []
for i, page in enumerate(pdfpage.create_pages(doc)):
interpreter.process_page(page)
# receive the ltpage object for this page
layout = device.get_result()
# layout is an ltpage object which may contain child objects like lttextbox, ltfigure, ltimage, etc.
text_content.append(parse_lt_objs(layout, (i+1), images_folder))
return text_content
def get_pages (pdf_doc, pdf_pwd=”, images_folder=’/tmp’):
“””process each of the pages in this pdf file and return a list of strings representing the text found in each page”””
return with_pdf(pdf_doc, _parse_pages, pdf_pwd, *tuple([images_folder]))
a = open(‘a.txt’,’a’)
for i in get_pages(‘/home/jamespei/nova.pdf’):
a.write(i)
a.close()

这段代码重点在于第128行,可以看到pdfminer是一种基于坐标来解析的框架,pdf中能解析的组件全都包括上下左右边缘的坐标,如x0 = lt_obj.bbox[0]就是lt_obj元素的左边缘的坐标,同理x1则为右边缘。以上代码的意思就是把所有x0且x1的坐标相差在20%以内的元素分成一组,这样就实现了从pdf文件中定向抽取内容。

----------------补充--------------------

有一个需要注意的地方,在解析有些pdf的时候会报这样的异常:pdfminer.pdfdocument.pdfencryptionerror: unknown algorithm: param={‘cf’: {‘stdcf’: {‘length’: 16, ‘cfm’: /aesv2, ‘authevent’: /docopen}}, ‘o’: ‘\xe4\xe74\xb86/\xa8)\xa6x\xe6\xa3/u\xdf\x0fwr\x9cph\xac\xae\x88b\x06_\xb0\x93@\x9f\x8d’, ‘filter’: /standard, ‘p’: -1340, ‘length’: 128, ‘r’: 4, ‘u’: ‘|utx#f\xc9v\x18\x87z\x10\xcb\xf5{\xa7\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00’, ‘v’: 4, ‘stmf’: /stdcf, ‘strf’: /stdcf}

从字面意思来看是因为这个pdf是一个加密的pdf,所以无法解析 ,但是如果直接打开pdf却是可以的并没有要求输密码什么的,原因是这个pdf虽然是加过密的,但密码是空,所以就出现了这样的问题。

解决这个的问题的办法是通过qpdf命令来解密文件(要确保已经安装了qpdf),要想在python中调用该命令只需使用call即可:

from subprocess import call
call(‘qpdf –password=%s –decrypt %s %s’ %(”, file_path, new_file_path), shell=true)

其中参数file_path是要解密的pdf的路径,new_file_path是解密后的pdf文件路径,然后使用解密后的文件去做解析就ok了

以上就是详解python使用pdfminer解析pdf实例的详细内容,更多请关注 第一php社区 其它相关文章!

Posted in 未分类