python简介pdf_pdf相关模块介绍与安装 Python提取PDF文字

pdf相关模块简介与安装

pypdf2模块

它可以读取、写入、分割、合并PDF文件,需要单独安装,不包含在Python标准模块里,官网:https://pythonhosted.org/PyPDF2/

pdfplumber模块

它可以更好地读取PDF文件内容,可以提取PDF中的表格,也是需要单独安装,不包含在Python标准模块里,官网:https://github.com/jsvine/pdfplumber/

发挥你的想象力!节约你的时间!有好多PDF要合并到同一个PDF里?从一堆财报中找到关键的呢些数据?批量加密PDF?把某些页面旋转一下?批量添加水印?……

直接使用pip命令安装PyPDF2和pdfplumber即可,鳄鱼君这里直接在pycharm的setting里面安装的,应该不会出现问题!

pdfplumber提取文字

利用pdfplumber提取文字,使用pdfplumber.open(PDF路径)打开PDF文件,pdf.pages[页数]获取页数,page.extract_text()获取文本内容

import pdfplumber

with pdfplumber.open('1.pdf') as pdf:

for page in pdf.pages:

print(page.extract_text())

# first_page=pdf.pages[0]

# print(first_page.extract_text())

pdfplumber提取表格

提取简单的表格

import pdfplumber

with pdfplumber.open('1.pdf') as pdf:

table_page=pdf.pages[0]

table=table_page.extract_table()

print(table)

提取多个简单表格

import pdfplumber

with pdfplumber.open('1.pdf') as pdf:

table_page=pdf.pages[0]

for table in table_page.extract_tables():

print(table)

extract_tables()方法接收table_settings参数,该参数是一个字典,可以规定表格的信息,可以查看官方文档,这里不详细介绍!

{

"vertical_strategy": "lines",

"horizontal_strategy": "lines",

"explicit_vertical_lines": [],

"explicit_horizontal_lines": [],

"snap_tolerance": 3,

"join_tolerance": 3,

"edge_min_length": 3,

"min_words_vertical": 3,

"min_words_horizontal": 1,

"keep_blank_chars": False,

"text_tolerance": 3,

"text_x_tolerance": None,

"text_y_tolerance": None,

"intersection_tolerance": 3,

"intersection_x_tolerance": None,

"intersection_y_tolerance": None,

}

PDF写入Excel表格

将pdf中提取到的table写入到Excel表格中

from openpyxl import Workbook

workbook=Workbook()

sheet=workbook.active

for row in table:

sheet.append(row)

workbook.save(filename='./new_book.xlsx')

对于不规整的PD表格,在提取的过程可能会出现空行和单词切分的问题,这里需要进行判断。对于空行,需要判断,非空行的才写入Excel表格,将列表中每个元素都连成一个字符串,如果还是一个空字符串那么就肯定是空行:

new_table=[]

for row in table:

if not ''.join([str(item) for item in row]) =='':

sheet.append(row)

合并单词,这里假设Excel表格中的前3列表示PDF中的1列数据,需要将Excel中的前3列合并:

new_row=[]

ner_row.append(''.join([str(item) if item else '' for item in row[:3]]))

new_row=row[3:]

new_table.append(new_row)

将前3列非None的内容合并为一个字符串,然后再添加到列表中。行内条件判断,就是一行代码完成条件判断:

x=5

y=x*2 if x<10 else 20

print(y)

如果x小于10,y值为x*2,否则y值为20,就这么理解!

未经允许不得转载:作者:鳄鱼君,

转载或复制请以 超链接形式 并注明出处 鳄鱼君。

原文地址:《pdf相关模块介绍与安装 Python提取PDF文字》 发布于2020-05-17

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值