Home > Backend Development > Python Tutorial > Python example detailed explanation of pdfplumber reading PDF and writing to Excel

Python example detailed explanation of pdfplumber reading PDF and writing to Excel

WBOY
Release: 2022-06-20 11:58:11
forward
6302 people have browsed it

This article brings you relevant knowledge about python, which mainly introduces the related issues about pdfplumber reading PDF and writing to Excel, including the installation of pdfplumber module, loading PDF, and Let’s take a look at some practical operations and so on. I hope it will be helpful to everyone.

Python example detailed explanation of pdfplumber reading PDF and writing to Excel

Recommended learning: python video tutorial

1. Python operation PDF 13 large library comparison

PDF ( Portable Document Format) is a portable document format that facilitates the dissemination of documents across operating systems. PDF documents follow a standard format, so there are many tools that can operate on PDF documents, and Python is no exception.

Comparison chart of Python operating PDF modules is as follows:

Python example detailed explanation of pdfplumber reading PDF and writing to Excel

This article mainly introduces pdfplumberFocus on PDF content extraction, such as text (position, font and colors, etc.) and shapes (rectangles, straight lines, curves), as well as the function of parsing tables.

2. pdfplumber module

Several other Python libraries help users extract information from PDFs. As a broad overview, pdfplumber differentiates itself from other PDF processing libraries by combining the following features:

  • Easy access to detailed information about each PDF object
  • Used for Higher-level, customizable methods for extracting text and tables
  • Tightly integrated visual debugging
  • Other useful utility features such as filtering objects by crop boxes

1. Installation

cmd console input:

pip install pdfplumber
Copy after login

Guide package:

import pdfplumber
Copy after login

Case PDF screenshot (two pages are not cut off):
Python example detailed explanation of pdfplumber reading PDF and writing to Excel

2. Load PDF

Read PDF code: pdfplumber.open("path/filename.pdf", password = "test", laparams = { "line_overlap": 0.7 })

Parameter interpretation:

  • password : To load a password-protected PDF, please pass the password keyword parameter
  • laparams: To set the layout analysis parameters to the layout engine of pdfminer.six, pass the laparams keyword argument

Case code:

import pdfplumberwith pdfplumber.open("./1.pdf") as pdf:
    print(pdf)
    print(type(pdf))
Copy after login

Output Result:

<pdfplumber.pdf.pdf><class></class></pdfplumber.pdf.pdf>
Copy after login

3. pdfplumber.PDF class

pdfplumber.PDF class represents a single PDF and has two main properties:

From PDF Get the metadata Returns a list containing pdfplumber.Page instances, each instance represents the information of each page of the PDF
Properties Description
##.metadata key/value pair dictionary from Info. Usually includes "CreationDate", "ModDate", "Producer", etc.
.pages

1. Read PDF document information (.metadata) :

import pdfplumberwith pdfplumber.open("./1.pdf") as pdf:
    print(pdf.metadata)
Copy after login
Run result:

{'Author': 'wangwangyuqing', 'Comments': '', 'Company': '', 'CreationDate': "D:20220330113508+03'35'", 'Creator': 'WPS 文字', 'Keywords': '', 'ModDate': "D:20220330113508+03'35'", 'Producer': '', 'SourceModified': "D:20220330113508+03'35'", 'Subject': '', 'Title': '', 'Trapped': 'False'}
Copy after login

2. Output the total number of pages

import pdfplumberwith pdfplumber.open("./1.pdf") as pdf:
    print(len(pdf.pages))
Copy after login
Running result:

2
Copy after login
4. pdfplumber.Page class

pdfplumber.PageThe class is the core of pdfplumber. Most operations revolve around this class. It has the following attributes:

AttributesDescriptionSequential page numbers, starting from 1 on the first page, starting from the second page 2, and so on analogy. The width of the page. The height of the page. Each of these properties is a list, each containing a dictionary for each such object embedded on the page. See "Objects" below for details.
.page_number
.width
.height
.objects/.chars/.lines/.rects/.curves/.figures/.images

Commonly used methods are as follows:

Method nameDescription is used to extract the text in the page and organize all the character objects on the page into That string returns all the words and their related informationExtract the tables of the pageWhen used for visual debugging, return an instance of the PageImage classBy default, the Page object caches its layout and object information to avoid reprocessing it. However, these cached properties can require a lot of memory when parsing large PDFs. You can use this method to flush the cache and free up memory.

1. 读取第一页宽度、高度等信息

import pdfplumberwith pdfplumber.open("./1.pdf") as pdf:
    first_page = pdf.pages[0]  # pdfplumber.Page对象的第一页
    # 查看页码
    print('页码:', first_page.page_number)
    # 查看页宽
    print('页宽:', first_page.width)
    # 查看页高
    print('页高:', first_page.height)
Copy after login

运行结果:

页码: 1页宽: 595.3页高: 841.9
Copy after login

2. 读取文本第一页

import pdfplumberwith pdfplumber.open("./1.pdf") as pdf:
    first_page = pdf.pages[0]  # pdfplumber.Page对象的第一页
    text = first_page.extract_text()
    print(text)
Copy after login

运行结果:

店铺名 价格 销量 地址
小罐茶旗舰店 449 474 安徽
零趣食品旗舰店 6.9 60000 福建
天猫超市 1304 3961 上海
天猫超市 139 25000 上海
天猫超市 930 692 上海
天猫超市 980 495 上海
天猫超市 139 100000 上海
三只松鼠旗舰店 288 25000 安徽
红小厨旗舰店 698 1767 北京
三只松鼠旗舰店 690 15000 安徽
一统领鲜旗舰店 1098 1580 上海
新大猩食品专营9.8 7000 湖南.......舰店
蟹纳旗舰店 498 1905 上海
三只松鼠坚果at茶 188 35000 安徽
嘉禹沪晓旗舰店 598 1517 上海
Copy after login

3. 读取表格第一页

import pdfplumberimport xlwtwith pdfplumber.open("1.pdf") as pdf:
    page_one = pdf.pages[0]  # PDF第一页
    table_1 = page_one.extract_table()  # 读取表格数据
    # 1. 创建Excel表对象
    workbook = xlwt.Workbook(encoding='utf8')
    # 2. 新建sheet表
    worksheet = workbook.add_sheet('Sheet1')
    # 3. 自定义列名
    col1 = table_1[0]
    # print(col1)# ['店铺名', '价格', '销量', '地址']
    # 4. 将列属性元组col写进sheet表单中第一行
    for i in range(0, len(col1)):
        worksheet.write(0, i, col1[i])
    # 5. 将数据写进sheet表单中
    for i in range(0, len(table_1[1:])):
        data = table_1[1:][i]
        for j in range(0, len(col1)):
            worksheet.write(i + 1, j, data[j])
    # 6. 保存文件分两种格式
    workbook.save('test.xls')
Copy after login

运行结果:

Python example detailed explanation of pdfplumber reading PDF and writing to Excel

三、实战操作

1. 提取单个PDF全部页数

测试代码:

import pdfplumberimport xlwtwith pdfplumber.open("1.pdf") as pdf:
    # 1. 把所有页的数据存在一个临时列表中
    item = []
    for page in pdf.pages:
        text = page.extract_table()
        for i in text:
            item.append(i)
    # 2. 创建Excel表对象
    workbook = xlwt.Workbook(encoding='utf8')
    # 3. 新建sheet表
    worksheet = workbook.add_sheet('Sheet1')
    # 4. 自定义列名
    col1 = item[0]
    # print(col1)# ['店铺名', '价格', '销量', '地址']
    # 5. 将列属性元组col写进sheet表单中第一行
    for i in range(0, len(col1)):
        worksheet.write(0, i, col1[i])
    # 6. 将数据写进sheet表单中
    for i in range(0, len(item[1:])):
        data = item[1:][i]
        for j in range(0, len(col1)):
            worksheet.write(i + 1, j, data[j])
    # 7. 保存文件分两种格式
    workbook.save('test.xls')
Copy after login

运行结果(上面得没截全):

Python example detailed explanation of pdfplumber reading PDF and writing to Excel

2. 批量提取多个PDF文件

Python example detailed explanation of pdfplumber reading PDF and writing to Excel

测试代码:

import pdfplumber
import xlwt
import os

# 一、获取文件下所有pdf文件路径
file_dir = r'E:\Python学习\pdf文件'
file_list = []
for files in os.walk(file_dir):
    # print(files)
    # ('E:\\Python学习\\pdf文件', [],
    #  ['1.pdf', '1的副本.pdf', '1的副本10.pdf', '1的副本11.pdf', '1的副本2.pdf', '1的副本3.pdf', '1的副本4.pdf', '1的副本5.pdf', '1的副本6.pdf',
    #   '1的副本7.pdf', '1的副本8.pdf', '1的副本9.pdf'])
    for file in files[2]:
        # 以. 进行分割如果后缀为PDF或pdf就拼接地址存入file_list
        if file.split(".")[1] == 'pdf' or file.split(".")[1] == 'PDF':
            file_list.append(file_dir + '\\' + file)

# 二、存入Excel
# 1. 把所有PDF文件的所有页的数据存在一个临时列表中
item = []
for file_path in file_list:
    with pdfplumber.open(file_path) as pdf:
        for page in pdf.pages:
            text = page.extract_table()
            for i in text:
                item.append(i)

# 2. 创建Excel表对象
workbook = xlwt.Workbook(encoding='utf8')
# 3. 新建sheet表
worksheet = workbook.add_sheet('Sheet1')
# 4. 自定义列名
col1 = item[0]
# print(col1)# ['店铺名', '价格', '销量', '地址']
# 5. 将列属性元组col写进sheet表单中第一行
for i in range(0, len(col1)):
    worksheet.write(0, i, col1[i])
# 6. 将数据写进sheet表单中
for i in range(0, len(item[1:])):
    data = item[1:][i]
    for j in range(0, len(col1)):
        worksheet.write(i + 1, j, data[j])
# 7. 保存文件分两种格式
workbook.save('test.xls')
Copy after login

运行结果(12个文件,一个文件50行总共600行):

Python example detailed explanation of pdfplumber reading PDF and writing to Excel

推荐学习:python视频教程

.extract_text()
.extract_words()
.extract_tables()
.to_image()
.close()

The above is the detailed content of Python example detailed explanation of pdfplumber reading PDF and writing to Excel. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:csdn.net
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template