欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

Python提取PDF內(nèi)容的方法(文本、圖像、線條等)

 更新時間:2019年09月25日 10:55:14   作者:查永春  
這篇文章主要介紹了Python提取PDF內(nèi)容的方法(文本、圖像、線條等),文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧

1.安裝PDFminer3k

使用pip 命令安裝

pip install pdfminer3k

2.編寫測試

你可以在這里獲得官方參考:PDFMiner

如果你不喜歡看英文的官方文檔,這里的翻譯也許對你有幫助:中文PDFMiner文檔

下面的程序,我拓展了官方給出的例子,你可以通過這個例子統(tǒng)計出來你的pdf文件一共包含哪些內(nèi)容,比如文本框,曲線,圖片等

#!/usr/bin/python
# -*- coding: utf-8 -*-

__author__ = 'yooongchun'

import sys
import importlib
importlib.reload(sys)

from pdfminer.pdfparser import PDFParser,PDFDocument
from pdfminer.pdfinterp import PDFResourceManager, PDFPageInterpreter
from pdfminer.converter import PDFPageAggregator
from pdfminer.layout import *
from pdfminer.pdfinterp import PDFTextExtractionNotAllowed

'''
解析pdf文件,獲取文件中包含的各種對象
'''


# 解析pdf文件函數(shù)
def parse(pdf_path):
  fp = open(pdf_path, 'rb') # 以二進(jìn)制讀模式打開
  # 用文件對象來創(chuàng)建一個pdf文檔分析器
  parser = PDFParser(fp)
  # 創(chuàng)建一個PDF文檔
  doc = PDFDocument()
  # 連接分析器 與文檔對象
  parser.set_document(doc)
  doc.set_parser(parser)

  # 提供初始化密碼
  # 如果沒有密碼 就創(chuàng)建一個空的字符串
  doc.initialize()

  # 檢測文檔是否提供txt轉(zhuǎn)換,不提供就忽略
  if not doc.is_extractable:
    raise PDFTextExtractionNotAllowed
  else:
    # 創(chuàng)建PDf 資源管理器 來管理共享資源
    rsrcmgr = PDFResourceManager()
    # 創(chuàng)建一個PDF設(shè)備對象
    laparams = LAParams()
    device = PDFPageAggregator(rsrcmgr, laparams=laparams)
    # 創(chuàng)建一個PDF解釋器對象
    interpreter = PDFPageInterpreter(rsrcmgr, device)

    # 用來計數(shù)頁面,圖片,曲線,figure,水平文本框等對象的數(shù)量
    num_page, num_image, num_curve, num_figure, num_TextBoxHorizontal = 0, 0, 0, 0, 0

    # 循環(huán)遍歷列表,每次處理一個page的內(nèi)容
    for page in doc.get_pages(): # doc.get_pages() 獲取page列表
      num_page += 1 # 頁面增一
      interpreter.process_page(page)
      # 接受該頁面的LTPage對象
      layout = device.get_result()
      for x in layout:
        if isinstance(x,LTImage): # 圖片對象
          num_image += 1
        if isinstance(x,LTCurve): # 曲線對象
          num_curve += 1
        if isinstance(x,LTFigure): # figure對象
          num_figure += 1
        if isinstance(x, LTTextBoxHorizontal): # 獲取文本內(nèi)容
          num_TextBoxHorizontal += 1 # 水平文本框?qū)ο笤鲆?
          # 保存文本內(nèi)容
          with open(r'test.txt', 'a') as f:
            results = x.get_text()
            f.write(results + '\n')
    print('對象數(shù)量:\n','頁面數(shù):%s\n'%num_page,'圖片數(shù):%s\n'%num_image,'曲線數(shù):%s\n'%num_curve,'水平文本框:%s\n'
       %num_TextBoxHorizontal)


if __name__ == '__main__':
  pdf_path = r'C:\Users\fanyu\Desktop\pdf\test.pdf'
  parse(pdf_path)
 

其實在上面的layout 對象中有更多的內(nèi)容可提取,這個自己按需來寫就好,然后對曲線,文本框等對象,都會有位置屬性,可直接獲取,自己debug 查看以下對象屬性獲取即可。

以上就是本文的全部內(nèi)容,希望對大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。

相關(guān)文章

最新評論