pdfplumber 提取 PDF 文本及表格

pdfplumber-0.5.12,适用于python 2.7、3.5、3.6.
官网链接在此:https://github.com/jsvine/pdfplumber

一、安装

pip install pdfplumber

二、使用

提取文本:pdf.page[0].extract_text()
提取表格:pdf.page[0].extract_tables()

提取文字与表格(去除空格),分别写入txt文档,代码如下:

import pdfplumber
path = 'path/to/file.pdf'
fileNames = os.path.splitext(path)

pdf = pdfplumber.open(path)
for page in pdf.pages:
    # 获取当前页面的全部文本信息,包括表格中的文字,写入txt文档
    # 直接得到字符串,包括了换行符【与PDF上的换行位置一致,而不是实际的“段落”】
	# print(page.extract_text())
	with open(fileNames[0] + '_txt.txt', 'a+') as m:
        m.write(page.extract_text())
    m.close()
    
    # 提取本页全部表格内容,删除空格等,写入txt文档
    # 得到的table是嵌套list类型
    for table in page.extract_tables():
        for row_old in table:  # 表中每一行
            row_new = []
            for i in range(len(row_old)):
                if row_old[i]:
                    row_new.append(row_old[i])
            # print(str(row_new).replace('\\n', '').decode('unicode-escape'))
            if len(row_new) != 0:
                with open(fileNames[0] + '_table.txt', 'a+') as f:
                    f.write(str(row_new).replace('\\n', '')+'\n')
                f.close()
pdf.close()
模块相关介绍:

https://github.com/jsvine/pdfplumber#pdfplumber-v0512

pdf.pdf 类
属性描述
.metadata元数据键/值对的字典,从PDF的Info预告片中提取。通常包括“CreationDate”,“ModDate”,“Producer”等。
.pages包含pdfplumber.Page每页加载一个实例的列表。
pdf.page 类
属性描述
.page_number页码
.width页面的宽度
.height页面的高度
.objects/ .chars/ .lines/.rects这些属性中的每一个都是一个列表,每个列表包含一个嵌入在页面上的每个此类对象的字典

关于方法和描述请见:https://github.com/jsvine/pdfplumber#the-pdfplumberpage-class

对象

每个实例pdfplumber.PDFpdfplumber.Page访问四种类型的PDF对象。以下属性各自返回匹配对象的Python列表:

对象含义
.chars文本字符
.annos注释文本字符
.lines一维直线
.rects二维矩形
.curves一系列连接点

关于属性和描述请见:https://github.com/jsvine/pdfplumber#objects

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值