最新国产好看的视频,伊人天堂AV在线,国产Aaaaaa视频,蜜臀视频在线观看一区,人妻av色图,密臀久久久精品影片,青青视频免费观看毛片,久草在线观看视,国产三级精品色情在线

Python使用pdfminer庫(kù)玩轉(zhuǎn)PDF文本提取

 更新時(shí)間:2025年02月05日 08:45:50   作者:正東AI  
pdfminer是一個(gè)開(kāi)源的Python第三方庫(kù),專門(mén)用于解析PDF文件,本文主要為大家詳細(xì)介紹了如何使用pdfminer實(shí)現(xiàn)PDF文本提取,有需要的小伙伴可以了解下

一、背景

在日常工作中,我們常常需要處理PDF文件,比如提取文本內(nèi)容、分析文檔結(jié)構(gòu)等。然而,PDF文件的格式復(fù)雜,直接提取信息并非易事。pdfminer庫(kù)應(yīng)運(yùn)而生,它能夠高效地解析PDF文件,提取文本、元數(shù)據(jù)、表格等信息,幫助我們輕松應(yīng)對(duì)各種PDF處理需求。接下來(lái),讓我們深入了解這個(gè)強(qiáng)大的工具。

二、什么是pdfminer

pdfminer是一個(gè)開(kāi)源的Python第三方庫(kù),專門(mén)用于解析PDF文件。它提供了豐富的API,可以精確提取文本、分析頁(yè)面布局、提取元數(shù)據(jù)等。它的核心功能是將PDF文件的內(nèi)容轉(zhuǎn)換為可操作的文本數(shù)據(jù),方便進(jìn)一步處理和分析。

三、如何安裝pdfminer

pdfminer是一個(gè)第三方庫(kù),可以通過(guò)以下命令行安裝:

pip install pdfminer.six

安裝完成后,可以通過(guò)以下命令確認(rèn)安裝是否成功:

python -c "import pdfminer; print(pdfminer.__version__)"

如果能夠正常輸出版本號(hào),說(shuō)明安裝成功。

四、簡(jiǎn)單庫(kù)函數(shù)使用方法

以下是pdfminer中常用的五個(gè)函數(shù)及其使用方法:

1. 提取文本

from pdfminer.high_level import extract_text

text = extract_text("example.pdf")
print(text)

extract_text函數(shù)用于從PDF文件中提取全部文本。

2. 獲取頁(yè)面布局信息

from pdfminer.layout import LAParams, LTTextBox, LTTextLine
from pdfminer.pdfpage import PDFPage
from pdfminer.pdfinterp import PDFResourceManager, PDFPageInterpreter
from pdfminer.converter import PDFPageAggregator

resource_manager = PDFResourceManager()
fake_file_handle = io.StringIO()
converter = PDFPageAggregator(resource_manager, laparams=LAParams())
page_interpreter = PDFPageInterpreter(resource_manager, converter)

???????with open("example.pdf", "rb") as pdf_file:
    for page in PDFPage.get_pages(pdf_file):
        page_interpreter.process_page(page)
        layout = converter.get_result()
        for lt_obj in layout:
            if isinstance(lt_obj, (LTTextBox, LTTextLine)):
                text = lt_obj.get_text()
                x, y, width, height = lt_obj.bbox
                font = lt_obj._objs[0].fontname
                font_size = lt_obj._objs[0].size
                print(f"Text: {text.strip()}, Position: ({x:.2f}, {y:.2f}), Font: {font}, Size: {font_size:.2f}")

這段代碼獲取文本塊的位置、字體和字號(hào)等信息。

3. 提取表格數(shù)據(jù)

from pdfminer.high_level import extract_text
import tabula

table_text = extract_text("table_example.pdf")
print(table_text)

tables = tabula.read_pdf("table_example.pdf", pages="all")
for df in tables:
    print(df)

使用pdfminer提取PDF文檔中的表格,并使用tabula提取表格數(shù)據(jù)。

4. 提取圖像

from pdfminer.pdfparser import PDFParser
from pdfminer.pdfdocument import PDFDocument
from pdfminer.pdftypes import PDFStream
import io
from PIL import Image

???????with open('example.pdf', 'rb') as file:
    parser = PDFParser(file)
    document = PDFDocument(parser)
    if document.is_extractable:
        for xref in document.xrefs:
            if xref.get_subtype() == '/Image':
                stream_obj = xref.get_object()
                if isinstance(stream_obj, PDFStream):
                    data = stream_obj.get_rawdata()
                    image = Image.open(io.BytesIO(data))
                    image.show()

提取PDF文檔中的圖像。

5. 提取元數(shù)據(jù)

from pdfminer.pdfparser import PDFParser
from pdfminer.pdfdocument import PDFDocument

def extract_metadata(pdf_path):
    with open(pdf_path, 'rb') as fh:
        parser = PDFParser(fh)
        doc = PDFDocument(parser)
        metadata = doc.info[0]
        for key, value in metadata.items():
            print(f"{key}: {value}")

extract_metadata('example.pdf')

提取PDF文件的元數(shù)據(jù)。

五、實(shí)際應(yīng)用場(chǎng)景

以下是pdfminer在不同場(chǎng)景中的應(yīng)用示例:

1. 法律文檔處理

from pdfminer.high_level import extract_text

def extract_legal_document_text(pdf_path):
    text = extract_text(pdf_path)
    return text

text = extract_legal_document_text('legal_document.pdf')
print(text)

在法律行業(yè),通過(guò)pdfminer提取和分析法律文檔中的文本和元數(shù)據(jù),自動(dòng)生成報(bào)告。

2. 財(cái)務(wù)報(bào)表分析

from pdfminer.layout import LAParams, LTTextBoxHorizontal
from pdfminer.pdfpage import PDFPage
from pdfminer.pdfinterp import PDFResourceManager, PDFPageInterpreter
from pdfminer.converter import PDFPageAggregator

def extract_financial_tables(pdf_path):
    with open(pdf_path, 'rb') as fh:
        rsrcmgr = PDFResourceManager()
        laparams = LAParams()
        device = PDFPageAggregator(rsrcmgr, laparams=laparams)
        interpreter = PDFPageInterpreter(rsrcmgr, device)

        for page in PDFPage.get_pages(fh, caching=True, check_extractable=True):
            interpreter.process_page(page)
            layout = device.get_result()
            for element in layout:
                if isinstance(element, LTTextBoxHorizontal):
                    print(element.get_text())

???????extract_financial_tables('financial_report.pdf')

在財(cái)務(wù)行業(yè),通過(guò)pdfminer提取財(cái)務(wù)報(bào)表中的表格數(shù)據(jù),進(jìn)行自動(dòng)化的數(shù)據(jù)分析和處理。

3. 研究論文數(shù)據(jù)提取

from pdfminer.layout import LAParams, LTTextBoxHorizontal, LTFigure
from pdfminer.pdfpage import PDFPage
from pdfminer.pdfinterp import PDFResourceManager, PDFPageInterpreter
from pdfminer.converter import PDFPageAggregator

def extract_research_paper_content(pdf_path):
    with open(pdf_path, 'rb') as fh:
        rsrcmgr = PDFResourceManager()
        laparams = LAParams()
        device = PDFPageAggregator(rsrcmgr, laparams=laparams)
        interpreter = PDFPageInterpreter(rsrcmgr, device)

        for page in PDFPage.get_pages(fh, caching=True, check_extractable=True):
            interpreter.process_page(page)
            layout = device.get_result()
            for element in layout:
                if isinstance(element, LTTextBoxHorizontal):
                    print(element.get_text())
                elif isinstance(element, LTFigure):
                    print("Figure found")

???????extract_research_paper_content('research_paper.pdf')

在學(xué)術(shù)研究中,通過(guò)pdfminer提取研究論文中的文本和圖表信息,輔助研究分析。

4. 文本逐頁(yè)提取

from pdfminer.pdfpage import PDFPage
from pdfminer.pdfinterp import PDFResourceManager, PDFPageInterpreter
from pdfminer.converter import TextConverter
from io import StringIO

def extract_text_by_page(pdf_path):
    resource_manager = PDFResourceManager()
    fake_file_handle = StringIO()
    converter = TextConverter(resource_manager, fake_file_handle)
    page_interpreter = PDFPageInterpreter(resource_manager, converter)

    with open(pdf_path, 'rb') as fh:
        for page in PDFPage.get_pages(fh, caching=True, check_extractable=True):
            page_interpreter.process_page(page)
            text = fake_file_handle.getvalue()
            yield text

    converter.close()
    fake_file_handle.close()

???????for page_text in extract_text_by_page('example.pdf'):
    print(page_text)

逐頁(yè)提取PDF文件中的文本,適用于需要逐頁(yè)處理的情況。

5. 提取目錄

from pdfminer.pdfparser import PDFParser
from pdfminer.pdfdocument import PDFDocument, PDFNoOutlines

def extract_toc(pdf_path):
    with open(pdf_path, 'rb') as file:
        parser = PDFParser(file)
        document = PDFDocument(parser)
        try:
            outlines = document.get_outlines()
            toc = []
            for (level, title, dest, a, se) in outlines:
                toc.append((level, title))
            return toc
        except PDFNoOutlines:
            return []

???????toc = extract_toc('example.pdf')
for item in toc:
    print(f"Level: {item[0]}, Title: {item[1]}")

提取PDF文檔的目錄,方便快速定位文檔結(jié)構(gòu)。

六、常見(jiàn)問(wèn)題及解決方案

以下是使用pdfminer時(shí)常見(jiàn)的問(wèn)題及解決方案:

文本提取為空

錯(cuò)誤信息 :extract_text返回空字符串。

原因 :PDF文件可能包含非文本內(nèi)容,或者文本被嵌入為圖像。

解決方案 :檢查PDF文件的內(nèi)容,確保文本是可提取的。如果文本嵌入為圖像,可以嘗試使用OCR工具(如`pytesseract

以上就是Python使用pdfminer庫(kù)玩轉(zhuǎn)PDF文本提取的詳細(xì)內(nèi)容,更多關(guān)于Python pdfminer PDF文本提取的資料請(qǐng)關(guān)注腳本之家其它相關(guān)文章!

相關(guān)文章

  • python基礎(chǔ)之字典

    python基礎(chǔ)之字典

    這篇文章主要介紹了python的字典,實(shí)例分析了Python中返回一個(gè)返回值與多個(gè)返回值的方法,需要的朋友可以參考下
    2021-10-10
  • Python3爬蟲(chóng)關(guān)于識(shí)別點(diǎn)觸點(diǎn)選驗(yàn)證碼的實(shí)例講解

    Python3爬蟲(chóng)關(guān)于識(shí)別點(diǎn)觸點(diǎn)選驗(yàn)證碼的實(shí)例講解

    在本篇文章里小編給大家整理了關(guān)于Python3爬蟲(chóng)關(guān)于識(shí)別點(diǎn)觸點(diǎn)選驗(yàn)證碼的實(shí)例講解內(nèi)容,需要的朋友們可以參考下。
    2020-07-07
  • Python設(shè)計(jì)模式之迭代器模式原理與用法實(shí)例分析

    Python設(shè)計(jì)模式之迭代器模式原理與用法實(shí)例分析

    這篇文章主要介紹了Python設(shè)計(jì)模式之迭代器模式原理與用法,結(jié)合具體實(shí)例形式分析了迭代器模式的概念、原理、定義及使用方法,代碼注釋說(shuō)明簡(jiǎn)單易懂,需要的朋友可以參考下
    2019-01-01
  • Pycharm連接遠(yuǎn)程服務(wù)器過(guò)程圖解

    Pycharm連接遠(yuǎn)程服務(wù)器過(guò)程圖解

    這篇文章主要介紹了Pycharm連接遠(yuǎn)程服務(wù)器過(guò)程圖解,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友可以參考下
    2020-04-04
  • mat矩陣和npy矩陣實(shí)現(xiàn)互相轉(zhuǎn)換(python和matlab)

    mat矩陣和npy矩陣實(shí)現(xiàn)互相轉(zhuǎn)換(python和matlab)

    這篇文章主要介紹了mat矩陣和npy矩陣實(shí)現(xiàn)互相轉(zhuǎn)換(python和matlab),具有很好的參考價(jià)值,希望對(duì)大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教
    2022-07-07
  • pandas.DataFrame選取/排除特定行的方法

    pandas.DataFrame選取/排除特定行的方法

    今天小編就為大家分享一篇pandas.DataFrame選取/排除特定行的方法,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過(guò)來(lái)看看吧
    2018-07-07
  • python 爬取英雄聯(lián)盟皮膚圖片

    python 爬取英雄聯(lián)盟皮膚圖片

    還記得那些年一起網(wǎng)吧開(kāi)黑通宵的日子嗎?《英雄聯(lián)盟》絕對(duì)是大學(xué)時(shí)期的風(fēng)靡游戲,即使畢業(yè)多年的大學(xué)同學(xué)相聚,難免不懷念一番當(dāng)時(shí)一起玩《英雄聯(lián)盟》的日子。今天就給大家分享一下英雄及皮膚圖片的爬蟲(chóng)。
    2021-05-05
  • Python實(shí)現(xiàn)網(wǎng)絡(luò)聊天室的示例代碼(支持多人聊天與私聊)

    Python實(shí)現(xiàn)網(wǎng)絡(luò)聊天室的示例代碼(支持多人聊天與私聊)

    這篇文章主要介紹了Python實(shí)現(xiàn)網(wǎng)絡(luò)聊天室的示例代碼(支持多人聊天與私聊),文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來(lái)一起學(xué)習(xí)學(xué)習(xí)吧
    2021-01-01
  • python實(shí)現(xiàn)嵌套列表平鋪的兩種方法

    python實(shí)現(xiàn)嵌套列表平鋪的兩種方法

    今天小編就為大家分享一篇python實(shí)現(xiàn)嵌套列表平鋪的兩種方法,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過(guò)來(lái)看看吧
    2018-11-11
  • Python OpenCV學(xué)習(xí)之特征點(diǎn)檢測(cè)與匹配詳解

    Python OpenCV學(xué)習(xí)之特征點(diǎn)檢測(cè)與匹配詳解

    提取圖像的特征點(diǎn)是圖像領(lǐng)域中的關(guān)鍵任務(wù),不管在傳統(tǒng)還是在深度學(xué)習(xí)的領(lǐng)域中,特征代表著圖像的信息,對(duì)于分類、檢測(cè)任務(wù)都是至關(guān)重要的。這篇文章主要為大家詳細(xì)介紹了OpenCV特征點(diǎn)檢測(cè)與匹配,需要的可以參考一下
    2022-01-01

最新評(píng)論

杭锦后旗| 泗水县| 奉新县| 奉贤区| 南江县| 平顺县| 定远县| 朝阳区| 七台河市| 铜鼓县| 闵行区| 乌恰县| 镇赉县| 民丰县| 双牌县| 扶沟县| 沁水县| 广汉市| 亳州市| 河西区| 金昌市| 砀山县| 泰宁县| 葫芦岛市| 曲周县| 尤溪县| 开封县| 桃江县| 子洲县| 容城县| 武汉市| 修武县| 枝江市| 临湘市| 汽车| 达拉特旗| 营山县| 怀柔区| 长汀县| 从江县| 万宁市|