网站首页 文章专栏 使用pdfplumber提取pdf数据.md
使用pdfplumber提取pdf数据.md
创建于:2021-07-04 08:50:26 更新于:2024-05-14 00:49:13 羽瀚尘 613

安装

pip3 install pdfplumber

简单使用

提取某一页

import pdfplumber
with pdfplumber.open("path/to/file.pdf") as pdf:
    first_page = pdf.pages[0]
    print(first_page.chars[0])

pdfplumber.pdf中包含了.metadata和.pages两个属性。
.metadata是一个包含pdf信息的字典。
.pages是一个包含页面信息的列表。

每个pdfplumber.page的类中包含了几个主要的属性。
.page_number 页码
.width 页面宽度
.height 页面高度
.objects/.chars/.lines/.rects 这些属性中每一个都是一个列表,每个列表都包含一个字典,每个字典用于说明页面中的对象信息, 包括直线,字符, 方格等位置信息。

.extract_text() 用来提页面中的文本,将页面的所有字符对象整理为的那个字符串
.extract_words() 返回的是所有的单词及其相关信息
.extract_tables() 提取页面的表格
.to_image() 用于可视化调试时,返回PageImage类的一个实例

import pdfplumber
import pandas as pd

with pdfplumber.open("中新科技:2015年年度报告摘要.PDF") as pdf:
    page = pdf.pages[1]   # 第一页的信息
    text = page.extract_text()
    print(text)
    table = page.extract_tables()
    for t in table:
        # 得到的table是嵌套list类型,转化成DataFrame更加方便查看和分析
        df = pd.DataFrame(t[1:], columns=t[0])
        print(df)

参考

https://blog.csdn.net/Elaine_jm/article/details/84841233