pdf信息提取

薛原@爬虫俱乐部

June 16, 2019

pdf是什么?

pdf(Portable Document Format的简称,意为“便携式文档格式”),是由Adobe Systems用于与应用程序、操作系统、硬件无关的方式进行文件交换所发展出的文件格式。

pdf的优点

  • 忠实地再现原稿的每一个字符、颜色以及图象。
  • 在不同的操作系统中都是通用的。
  • 可以将文字、字型、格式、颜色及独立于设备和分辨率的图形图像等封装在一个文件中,还可以包含超文本链接、声音和动态影像等电子信息,支持特长文件,集成度和安全可靠性都较高。
  • 提供了个性化的阅读方式。

从pdf中我们能得到什么?

  • 年报
  • 上市公司公告
  • 企业社会责任报告
  • ……

提取pdf信息

一、命令行工具xpdf

xpdf将pdf转为txt

pdftotext temp.pdf temp.txt
pdftotext
pdftotext

二、Python解析pdf

webdriver

Firefox解析pdf

  • Firefox浏览器强大的解析功能能够将pdf的内容转换为网页
  • 通过webdriver调用Firefox打开pdf文件并进行提取

Firefox
Firefox

chrome
chrome

webdriver+Firefox

解析pdf的库

pdfminer3k

tabula

三、Stata提取pdf信息

wordconvert命令

wordconvert功能

  • 与powershell做交互,调用MS Word端口,实现文件格式转换
  • 1.0版:docx、rtf、doc、html等格式的文件转换
  • 2.0版:可对pdf文件进行转换
  • 3.0版:加入报错信息,开发中

wordconvert准备工作

  • windows系统
  • 配置powershell
  • 装有MS Word 2013及以上版本
  • 没安装过WPS,尤其是抢鲜版

配置powershell

  • 以管理员身份运行powershell
  • 将执行策略(ExecutionPolicy)设置为Remotesigned
set-ExecutionPolicy Remotesigned

wordconvert命令

wordconvert temp.pdf temp.html, replace encoding("gb18030")
temp.html源代码
temp.html源代码

解析源代码

clear
set obs 1
gen v = fileread("temp.html")
replace v = ustrfrom(v, "gb18030", 1)
replace v = ustrregexra(v, "\r|\n", "")
replace v = ustrregexra(v, "<style>.*?</style>", "")
replace v = ustrregexra(v, "<.*?>", "")
compress

谢谢