最新公告
  • 欢迎您光临起源地模板网,本站秉承服务宗旨 履行“站长”责任,销售只是起点 服务永无止境!立即加入钻石VIP
  • 进阶PDF,就用Python(pdfminer.six和pdfplumber模块)

    正文概述    2020-05-14   407

    继上篇讲过PDF中的PyPDF2模块后,本篇为大家带来pdfminer.sixpdfplumber模块的详细讲解。


    pdfminer.six


    PDFMiner的操作门槛比较高,需要部分了解PDF的文档结构模型,适合定制开发复杂的内容处理工具。

    平时直接用PDFMiner比较少,这里只演示基本的文档内容操作:


    import pathlib from pdfminer.pdfparser import PDFParser from pdfminer.pdfdocument import PDFDocument from pdfminer.pdfpage import PDFPage from pdfminer.pdfinterp import PDFResourceManager from pdfminer.pdfinterp import PDFPageInterpreter from pdfminer.pdfdevice import PDFDevice from pdfminer.layout import LAParams, LTTextBox, LTFigure, LTImage from pdfminer.converter import PDFPageAggregator path = list(pathlib.Path.cwd().parents)[1].joinpath('data/automate/002pdf') f_path = path.joinpath('2020-新冠肺炎疫情对中国连锁餐饮行业的影响调研报告-中国连锁经营协会.pdf') with open(f_path, 'rb') as f:    parser = PDFParser(f)    doc = PDFDocument(parser)    rsrcmgr = PDFResourceManager()    laparams = LAParams()    device = PDFPageAggregator(rsrcmgr, laparams=laparams)    interpreter = PDFPageInterpreter(rsrcmgr, device)    for page in PDFPage.create_pages(doc):        interpreter.process_page(page)        layout = device.get_result()        for x in layout:            # 获取文本对象            if isinstance(x, LTTextBox):                print(x.get_text().strip())            # 获取图片对象            if isinstance(x,LTImage):                print('这里获取到一张图片')            # 获取 figure 对象            if isinstance(x,LTFigure):                print('这里获取到一个 figure 对象')


    虽然pdfminer使用门槛较高,但遇到复杂情况,最后还得用它。目前开源模块中,它对PDF的支持应该是最全的了。

    下面这个pdfplumber就是基于pdfminer.six开发的模块,降低了使用门槛。


    pdfplumber


    相比pdfminer.six,pdfplumber提供了更便捷的PDF内容抽取接口。

    日常工作中常用的操作,比如:

    • 提取PDF内容,保存到txt文件

    • 提取PDF中的表格到Excel

    • 提取PDF中的图片

    • 提取PDF中的图表


    提取PDF内容,保存到txt文件


    import pathlib import pdfplumber path = list(pathlib.Path.cwd().parents)[1].joinpath('data/automate/002pdf') f_path = path.joinpath('2020-新冠肺炎疫情对中国连锁餐饮行业的影响调研报告-中国连锁经营协会.pdf') out_path = path.joinpath('002pdf_out.txt') with pdfplumber.open(f_path) as pdf, open(out_path ,'a') as txt:    for page in pdf.pages:        textdata = page.extract_text()        txt.write(textdata)


    提取PDF中的表格到Excel


    import pathlib import pdfplumber from openpyxl import Workbook path = list(pathlib.Path.cwd().parents)[1].joinpath('data/automate/002pdf') f_path = path.joinpath('2020-新冠肺炎疫情对中国连锁餐饮行业的影响调研报告-中国连锁经营协会.pdf') out_path = path.joinpath('002pdf_excel.xlsx') wb = Workbook() sheet = wb.active with pdfplumber.open(f_path) as pdf:    for i in range(19, 22):        page = pdf.pages[i]        table = page.extract_table()        for row in table:            sheet.append(row) wb.save(out_path)


    上面用到了openpyxl的功能创建了一个Excel文件,之前有单独文章介绍它。


    提取PDF中的图片


    import pathlib import pdfplumber from PIL import Image path = list(pathlib.Path.cwd().parents)[1].joinpath('data/automate/002pdf') f_path = path.joinpath('2020-疫情影响下的中国社区趋势研究-艾瑞.pdf') out_path = path.joinpath('002pdf_images.png') with pdfplumber.open(f_path) as pdf, open(out_path, 'wb') as fout:    page = pdf.pages[10]    # for img in page.images:    im = page.to_image()    im.save(out_path, format='PNG')    imgs = page.images    for i, img in enumerate(imgs):        size = img['width'], img['height']        data = img['stream'].get_data()        out_path = path.joinpath(f'002pdf_images_{i}.png')        with open(out_path, 'wb') as fimg_out:            fimg_out.write(data)


    上面用到了PIL(Pillow)的功能处理图片。


    提取PDF中的图表


    图表与图像不同,指的是类似直方图、饼图之类的数据生成图。


    import pathlib import pdfplumber from PIL import Image path = list(pathlib.Path.cwd().parents)[1].joinpath('data/automate/002pdf') f_path = path.joinpath('2020-新冠肺炎疫情对中国连锁餐饮行业的影响调研报告-中国连锁经营协会.pdf') out_path = path.joinpath('002pdf_figures.png') with pdfplumber.open(f_path) as pdf, open(out_path, 'wb') as fout:    page = pdf.pages[7]    im = page.to_image()    im.save(out_path, format='PNG')    figures = page.figures    for i, fig in enumerate(figures):        size = fig['width'], fig['height']        crop = page.crop((fig['x0'], fig['top'], fig['x1'], fig['bottom']))        img_crop = crop.to_image()        out_path = path.joinpath(f'002pdf_figures_{i}.png')        img_crop.save(out_path, format='png')    im.draw_rects(page.extract_words(), stroke='yellow')    im.draw_rects(page.images, stroke='blue')    im.draw_rects(page.figures) im # show in notebook


    另外需要说明的是,PDF标准规范由Adobe公司主导。

    平时我们不需要参考规范,但如果遇到一些较复杂的场景,尤其是模块没有直接支持,就只能硬着头皮翻阅文档了。文档是公开的,可以去搜索引擎搜索关键词:pdf_reference_1-7.pdf


    今天的分享到这里就结束了,希望能让大家对使用PDF有了更多的理解和运用。更多Python学习,就在起源地模板网教学中心


    起源地下载网 » 进阶PDF,就用Python(pdfminer.six和pdfplumber模块)

    常见问题FAQ

    免费下载或者VIP会员专享资源能否直接商用?
    本站所有资源版权均属于原作者所有,这里所提供资源均只能用于参考学习用,请勿直接商用。若由于商用引起版权纠纷,一切责任均由使用者承担。更多说明请参考 VIP介绍。
    提示下载完但解压或打开不了?
    最常见的情况是下载不完整: 可对比下载完压缩包的与网盘上的容量,若小于网盘提示的容量则是这个原因。这是浏览器下载的bug,建议用百度网盘软件或迅雷下载。若排除这种情况,可在对应资源底部留言,或 联络我们.。
    找不到素材资源介绍文章里的示例图片?
    对于PPT,KEY,Mockups,APP,网页模版等类型的素材,文章内用于介绍的图片通常并不包含在对应可供下载素材包内。这些相关商业图片需另外购买,且本站不负责(也没有办法)找到出处。 同样地一些字体文件也是这种情况,但部分素材会在素材包内有一份字体下载链接清单。
    模板不会安装或需要功能定制以及二次开发?
    请QQ联系我们

    发表评论

    还没有评论,快来抢沙发吧!

    如需帝国cms功能定制以及二次开发请联系我们

    联系作者

    请选择支付方式

    ×
    迅虎支付宝
    迅虎微信
    支付宝当面付
    余额支付
    ×
    微信扫码支付 0 元