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

首先说明的是解析PDF是非常蛋疼的事,即使是PDFMiner对于格式不工整的PDF解析效果也不怎么样,所以连PDFMiner的开发者都吐槽PDF is evil. 不过这些并不重要。官方文档在此:http://www.unixuser.org/~euske/python/pdfminer/index.html

一.安装:

1.首先下载源文件包http://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用于保存共享内容例如字体或图片。

Figure 1. Relationships between PDFMiner classes

比较重要的是Layout,主要包括以下这些组件:

LTPage

Represents an entire page. May contain child objects like LTTextBox, LTFigure, LTImage, LTRect, LTCurve and LTLine.

LTTextBox

Represents a group of text chunks that can be contained in a rectangular area. Note that this box is created by geometric analysis and does not necessarily represents a logical boundary of the text. It contains a list of LTTextLine objects. get_text() method returns the text content.

LTTextLine

Contains a list of LTChar objects that represent a single text line. The characters are aligned either horizontaly or vertically, depending on the text's writing mode. get_text() method returns the text content.

LTChar

LTAnno

Represent an actual letter in the text as a Unicode string. Note that, while a LTChar object has actual boundaries, LTAnno objects does not, as these are "virtual" characters, inserted by a layout analyzer according to the relationship between two characters (e.g. a space).

LTFigure

Represents an area used by PDF Form objects. PDF Forms can be used to present figures or pictures by embedding yet another PDF document within a page. Note that LTFigure objects can appear recursively.

LTImage

Represents an image object. Embedded images can be in JPEG or other formats, but currently PDFMiner does not pay much attention to graphical objects.

LTLine

Represents a single straight line. Could be used for separating text or figures.

LTRect

Represents a rectangle. Could be used for framing another pictures or figures.

LTCurve

Represents a generic Bezier curve.

Figure 2. Layout objects and its tree structure

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

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

1 #!/usr/bin/python

2

3 importsys4 importos5 from binascii importb2a_hex6

7

8 ###

9 ### pdf-miner requirements

10 ###

11

12 from pdfminer.pdfparser importPDFParser13 from pdfminer.pdfdocument importPDFDocument, PDFNoOutlines14 from pdfminer.pdfpage importPDFPage15 from pdfminer.pdfinterp importPDFResourceManager, PDFPageInterpreter16 from pdfminer.converter importPDFPageAggregator17 from pdfminer.layout importLAParams, LTTextBox, LTTextLine, LTFigure, LTImage, LTChar18

19 def with_pdf (pdf_doc, fn, pdf_pwd, *args):20 """Open the pdf document, and apply the function, returning the results"""

21 result =None22 try:23 #open the pdf file

24 fp = open(pdf_doc, 'rb')25 #create a parser object associated with the file object

26 parser =PDFParser(fp)27 #create a PDFDocument object that stores the document structure

28 doc =PDFDocument(parser, pdf_pwd)29 #connect the parser and document objects

30 parser.set_document(doc)31 #supply the password for initialization

32

33 ifdoc.is_extractable:34 #apply the function and return the result

35 result = fn(doc, *args)36

37 #close the pdf file

38 fp.close()39 exceptIOError:40 #the file doesn't exist or similar problem

41 pass

42 returnresult43

44

45 ###

46 ### Table of Contents

47 ###

48

49 def_parse_toc (doc):50 """With an open PDFDocument object, get the table of contents (toc) data51 [this is a higher-order function to be passed to with_pdf()]"""

52 toc =[]53 try:54 outlines =doc.get_outlines()55 for (level,title,dest,a,se) inoutlines:56 toc.append( (level, title) )57 exceptPDFNoOutlines:58 pass

59 returntoc60

61 def get_toc (pdf_doc, pdf_pwd=''):62 """Return the table of contents (toc), if any, for this pdf file"""

63 returnwith_pdf(pdf_doc, _parse_toc, pdf_pwd)64

65

66 ###

67 ### Extracting Images

68 ###

69

70 def write_file (folder, filename, filedata, flags='w'):71 """Write the file data to the folder and filename combination72 (flags: 'w' for write text, 'wb' for write binary, use 'a' instead of 'w' for append)"""

73 result =False74 ifos.path.isdir(folder):75 try:76 file_obj =open(os.path.join(folder, filename), flags)77 file_obj.write(filedata)78 file_obj.close()79 result =True80 exceptIOError:81 pass

82 returnresult83

84 defdetermine_image_type (stream_first_4_bytes):85 """Find out the image file type based on the magic number comparison of the first 4 (or 2) bytes"""

86 file_type =None87 bytes_as_hex =b2a_hex(stream_first_4_bytes)88 if bytes_as_hex.startswith('ffd8'):89 file_type = '.jpeg'

90 elif bytes_as_hex == '89504e47':91 file_type = '.png'

92 elif bytes_as_hex == '47494638':93 file_type = '.gif'

94 elif bytes_as_hex.startswith('424d'):95 file_type = '.bmp'

96 returnfile_type97

98 defsave_image (lt_image, page_number, images_folder):99 """Try to save the image data from this LTImage object, and return the file name, if successful"""

100 result =None101 iflt_image.stream:102 file_stream =lt_image.stream.get_rawdata()103 iffile_stream:104 file_ext = determine_image_type(file_stream[0:4])105 iffile_ext:106 file_name = ''.join([str(page_number), '_', lt_image.name, file_ext])107 if write_file(images_folder, file_name, file_stream, flags='wb'):108 result =file_name109 returnresult110

111

112 ###

113 ### Extracting Text

114 ###

115

116 def to_bytestring (s, enc='utf-8'):117 """Convert the given unicode string to a bytestring, using the standard encoding,118 unless it's already a bytestring"""

119 ifs:120 ifisinstance(s, str):121 returns122 else:123 returns.encode(enc)124

125 def update_page_text_hash (h, lt_obj, pct=0.2):126 """Use the bbox x0,x1 values within pct% to produce lists of associated text within the hash"""

127

128 x0 =lt_obj.bbox[0]129 x1 = lt_obj.bbox[2]130

131 key_found =False132 for k, v inh.items():133 hash_x0 =k[0]134 if x0 >= (hash_x0 * (1.0-pct)) and (hash_x0 * (1.0+pct)) >=x0:135 hash_x1 = k[1]136 if x1 >= (hash_x1 * (1.0-pct)) and (hash_x1 * (1.0+pct)) >=x1:137 #the text inside this LT* object was positioned at the same

138 #width as a prior series of text, so it belongs together

139 key_found =True140 v.append(to_bytestring(lt_obj.get_text()))141 h[k] =v142 if notkey_found:143 #the text, based on width, is a new series,

144 #so it gets its own series (entry in the hash)

145 h[(x0,x1)] =[to_bytestring(lt_obj.get_text())]146

147 returnh148

149 def parse_lt_objs (lt_objs, page_number, images_folder, text=[]):150 """Iterate through the list of LT* objects and capture the text or image data contained in each"""

151 text_content =[]152

153 page_text = {} #k=(x0, x1) of the bbox, v=list of text strings within that bbox width (physical column)

154 for lt_obj inlt_objs:155 if isinstance(lt_obj, LTTextBox) orisinstance(lt_obj, LTTextLine):156 #text, so arrange is logically based on its column width

157 page_text =update_page_text_hash(page_text, lt_obj)158 elifisinstance(lt_obj, LTImage):159 #an image, so save it to the designated folder, and note its place in the text

160 saved_file =save_image(lt_obj, page_number, images_folder)161 ifsaved_file:162 #use html style tag to mark the position of the image within the text

163 text_content.append(''+os.path.join(images_folder, saved_file)+'')164 else:165 print >> sys.stderr, "error saving image on page", page_number, lt_obj.__repr__

166 elifisinstance(lt_obj, LTFigure):167 #LTFigure objects are containers for other LT* objects, so recurse through the children

168 text_content.append(parse_lt_objs(lt_obj, page_number, images_folder, text_content))169

170 for k, v in sorted([(key,value) for (key,value) inpage_text.items()]):171 #sort the page_text hash by the keys (x0,x1 values of the bbox),

172 #which produces a top-down, left-to-right sequence of related columns

173 text_content.append(''.join(v))174

175 return '\n'.join(text_content)176

177

178 ###

179 ### Processing Pages

180 ###

181

182 def_parse_pages (doc, images_folder):183 """With an open PDFDocument object, get the pages and parse each one184 [this is a higher-order function to be passed to with_pdf()]"""

185 rsrcmgr =PDFResourceManager()186 laparams =LAParams()187 device = PDFPageAggregator(rsrcmgr, laparams=laparams)188 interpreter =PDFPageInterpreter(rsrcmgr, device)189

190 text_content =[]191 for i, page inenumerate(PDFPage.create_pages(doc)):192 interpreter.process_page(page)193 #receive the LTPage object for this page

194 layout =device.get_result()195 #layout is an LTPage object which may contain child objects like LTTextBox, LTFigure, LTImage, etc.

196 text_content.append(parse_lt_objs(layout, (i+1), images_folder))197

198 returntext_content199

200 def get_pages (pdf_doc, pdf_pwd='', images_folder='/tmp'):201 """Process each of the pages in this pdf file and return a list of strings representing the text found in each page"""

202 return with_pdf(pdf_doc, _parse_pages, pdf_pwd, *tuple([images_folder]))203

204 a = open('a.txt','a')205 for i in get_pages('/home/jamespei/nova.pdf'):206 a.write(i)207 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即可:

1 from subprocess importcall2 call('qpdf --password=%s --decrypt %s %s' %('', file_path, new_file_path), shell=True)

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

python怎么读取pdf为文本_Python使用PDFMiner解析PDF相关推荐

  1. python处理pdf实例_python使用pdfminer解析pdf文件的方法示例

    最近要做个从 pdf 文件中抽取文本内容的工具,大概查了一下 python 里可以使用 pdfminer 来实现.下面就看看怎样使用吧. PDFMiner是一个可以从PDF文档中提取信息的工具.与其他 ...

  2. python 读取pdf cid_python使用pdfminer解析pdf文件的方法示例

    最近要做个从 pdf 文件中抽取文本内容的工具,大概查了一下 python 里可以使用 pdfminer 来实现.下面就看看怎样使用吧. PDFMiner是一个可以从PDF文档中提取信息的工具.与其他 ...

  3. python怎么读取pdf为文本_python怎么读取pdf文本内容

    python读取pdf文本内容的方法:首先打开相应的python脚本文件:然后使用PDFMiner工具来读取pdf文本内容:最后通过print输出读取后的内容即可. python读取pdf文本内容 p ...

  4. python 读取鼠标选中文本_python怎么读取文本文件

    python怎么读取文本文件? 文件的读取 步骤:打开 -- 读取 -- 关闭 1 >>> f = open('/tmp/test.txt') 2 >>> f.re ...

  5. 读取Excel的文本框,除了解析xml还可以用python调用VBA

    作者:小小明 Python读取Excel的文本框 基本需求 今天看到了一个很奇怪的问题,要读取Excel文件的文本框中的文本,例如这种: 本以为openxlpy可以读取,但查看openxlpy官方文档 ...

  6. python xlrd读取文件报错_python利用xlrd读取excel文件始终报错原因

    1.代码按照网上百度的格式进行书写如下: 但运行后,始终报错如下: 百度了xlrd网页: 分明支持xls和xlsx两种格式的文件,但运行始终报错. 最后找到原因是因为我所读取的文件虽然是以.xls命名 ...

  7. python批量读取excel表格数据_Python读取Excel数据并生成图表过程解析

    一.需求背景 自己一直在做一个周基金定投模拟,每周需要添加一行数据,并生成图表.以前一直是用Excel实现的.但数据行多后,图表大小调整总是不太方便,一般只能通过缩放比例解决. 二.需求实现目标 通过 ...

  8. python 批量读取xlsx并合并_python合并多个excel表格数据-python如何读取多个excel合并到一个excel中...

    python如何读取多个excel合并到一个excel中 思路 利用python xlrd包读取excle文件,然后将文件内容存入一个列表中,再利用xlsxwriter将内容写入到一个新的excel文 ...

  9. python如何读取二进制文件为图片_Python二进制文件读取并转换

    Python二进制文件读取并转换 Python二进制文件读取并转换 标签(空格分隔): python 本文所用环境: Python 3.6.5 |Anaconda custom (64-bit)| 引 ...

  10. Python 3.6 中使用pdfminer解析pdf文件

    所使用python环境为最新的3.6版本 一.安装pdfminer模块 安装anaconda后,直接可以通过pip安装 pip install pdfminer3k 如上图所示安装成功. 二.在IDE ...

最新文章

  1. springboot集成mybatis-generator时候遇到的问题
  2. OpenvSwitch — Overview
  3. 无人驾驶系列】光学雷达(LiDAR)在无人驾驶技术中的应用
  4. oracle11g ora 29927,Oracle11gR2使用RMANDuplicate复制数据库
  5. C/C++之#ifdef、#if、#if defined的区别
  6. onclick的值传给php,php – 从onclick事件将HTML属性传递给jQuery函数
  7. 【BERT】源码分析(PART I)
  8. C# 从类库中获取资源图片,把图片资源保存到类库中
  9. 用c语言判断计算机是大端模式还是小端模式
  10. paip.验证码识别的意义
  11. 高德地图轨迹方向_阿里巴巴高德地图首席科学家任小枫:高精算法推动高精地图落地...
  12. 情迁机器人Tim_情迁机器人插件-情迁机器人app下载V1.5.0安卓版-西西软件下载
  13. python绘制网络拓扑图_python 画网络拓扑图
  14. 工业无线开关量信号传输器
  15. A题 转换AV号(avtobv)
  16. 微服务和SpringCloud的关系
  17. 服务器能当电脑用吗?与普通电脑有何区别?
  18. jQuery判断元素是否显示 是否隐藏
  19. 基于javaweb+mysql的+JPA图书馆座位占座预约管理系统(管理员、老师、
  20. 翻译: 4.多层感知器 pytorch

热门文章

  1. Synonyms 中文近义词工具包 -- 支持文本对齐,推荐算法,相似度计算,语义偏移,关键字提取,概念提取,自动摘要,搜索引擎等
  2. regester正则用法_Regester下载|Regester(正则表达式测试器) 官方版v2.0.1 下载_当游网...
  3. html 之 img hspace 和 vspace 属性
  4. 小米手机证书信任设置在哪里_通过此设置帮助更快地启动小米手机
  5. iOS 获取APP名称 版本等
  6. python中def demo是什么意思_Python def函数的定义、使用及参数传递实现代码
  7. Vue入门项目:学生管理系统之班级管理 【含源码】
  8. 文件分配方式-索引分配
  9. Windows设置调节音量的快捷键
  10. Python基础语法详解