python读取pdf文件

本文详细介绍Pdfplumber库的功能和使用方法,包括安装步骤、基本操作、文本与表格提取技巧及参数设置。Pdfplumber是一个强大的PDF处理工具,能够解析文本、字符、表格和页面布局,适用于数据提取和PDF文档分析。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

pdfplumber简介

Pdfplumber是一个可以处理pdf格式信息的库。可以查找关于每个文本字符、矩阵、和行的详细信息,也可以对表格进行提取并进行可视化调试。

文档参考https://github.com/jsvine/pdfplumber

pdfplumber安装

安装直接采用pip即可。命令行中输入

pip install pdfplumber

如果要进行可视化的调试,则需要安装ImageMagick。
Pdfplumber GitHub: https://github.com/jsvine/pdfplumber
ImageMagick地址:
http://docs.wand-py.org/en/latest/guide/install.html#install-imagemagick-windows
(官网地址没有6x, 6x地址:https://imagemagick.org/download/binaries/)

(注意:我在装ImageMagick,使用起来是报错了, 网上参照了这里 了解到应该装6x版,7x版会报错。故找了6x的地址如上。)

在使用to_image函数输出图片时,如果报错DelegateException。则安装GhostScript 32位。(注意,一定要下载32位版本,哪怕Windows和python的版本是64位的。)
GhostScript: https://www.ghostscript.com/download/gsdnld.html

 

简单使用

import pdfplumber
with pdfplumber.open("path/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类的一个实例

 

常用参数

table_settings

表提取设置

默认情况下,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,
}
表提取策略

vertical_strategy 和 horizontal_strategy 的参数选项 

"lines"Use the page's graphical lines — including the sides of rectangle objects — as the borders of potential table-cells.
"lines_strict"Use the page's graphical lines — but not the sides of rectangle objects — as the borders of potential table-cells.
"text"For vertical_strategy: Deduce the (imaginary) lines that connect the left, right, or center of words on the page, and use those lines as the borders of potential table-cells. For horizontal_strategy, the same but using the tops of words.
"explicit"Only use the lines explicitly defined in explicit_vertical_lines / explicit_horizontal_lines.
 
 

举例使用

读取文字

import pdfplumber
import pandas as pd

with pdfplumber.open("E:\\600aaa_2.pdf") as pdf:
    page_count = len(pdf.pages)
    print(page_count)  # 得到页数
    for page in pdf.pages:
        print('---------- 第[%d]页 ----------' % page.page_number)
        # 获取当前页面的全部文本信息,包括表格中的文字
        print(page.extract_text())

 读取表格

import pdfplumber
import pandas as pd
import re

with pdfplumber.open("E:\\600aaa_1.pdf") as pdf:
    page_count = len(pdf.pages)
    print(page_count)  # 得到页数
    for page in pdf.pages:
        print('---------- 第[%d]页 ----------' % page.page_number)

        for pdf_table in page.extract_tables(table_settings={"vertical_strategy": "text",
                                                         "horizontal_strategy": "lines",
                                                        "intersection_tolerance":20}): # 边缘相交合并单元格大小

            # print(pdf_table)
            for row in pdf_table:
                # 去掉回车换行
                print([re.sub('\s+', '', cell) if cell is not None else None for cell in row])

 

 

 

部分参照:https://blog.youkuaiyun.com/Elaine_jm/article/details/84841233

 

转载于:https://www.cnblogs.com/xiao-apple36/p/10496707.html

<think>我们正在处理用户的问题:“我想使用Python读取PDF文件的内容 请问Python 如何读取 PDF 文件内容” 根据用户的问题,我们需要提供使用Python读取PDF文件内容的方法。 根据之前提供的引用,有两种方法: 引用[1]:使用PyPDF2库,并给出了读取第1-100页内容的示例代码。 引用[2]:使用Spire.PDF for Python库,并提到它可以提取文本和图片,还支持格式转换。 因此,我们可以介绍两种方法,并给出示例代码。 注意:用户要求使用中文回答,并且按照系统级指令,数学公式使用$...$或$$...$$格式(但本问题可能不涉及数学公式,所以不需要)。 另外,根据指令,我们需要在回答末尾生成相关问题。 回答结构: 1. 介绍两种常用的方法(两个库) 2. 分别给出安装命令和示例代码 3. 说明两种方法的优缺点或适用场景 4. 生成相关问题 注意:引用标识的使用。在引用到之前提供的参考内容时,在末尾添加引用标识,例如[^1]或[^2]。 但是,我们提供的引用是来自用户给出的参考,所以我们可以这样引用。 然而,用户提供的两个引用都是关于读取PDF的,我们可以直接使用。 但是请注意,用户提供的引用内容中,引用[1]使用的是PyPDF2,引用[2]使用的是Spire.PDF for Python。 我们还需要注意,Spire.PDF for Python是一个商业库,有免费版但可能有限制。 因此,我们在回答中应该说明这一点。 另外,我们还可以提到其他库,如pdfplumber(它也是常用的,并且提取文本效果更好),但用户没有提供引用,我们可以根据我们的知识补充,但要注意指令要求“尽量保证回答真实可靠”,所以如果我们知道的话可以补充,但如果没有把握,可以只根据用户提供的引用。 但是,用户的问题只是要求读取内容,并没有指定是文本还是图片,所以我们可以分别介绍。 考虑到用户提供的引用中,引用[2]提到了提取文本和图片,而引用[1]只提取文本(并且可能效果一般),我们可以这样组织: 步骤: 1. 使用PyPDF2(免费,但文本提取效果可能不佳,特别是对于复杂格式) 2. 使用Spire.PDF for Python(商业库,免费版有限制,但功能强大) 3. 另外,也可以提一下pdfplumber(因为它是免费的,并且在提取文本方面表现较好),但注意用户没有提供这个引用,我们可以简单提一下,作为补充。 注意:根据指令,我们应尽可能参考用户上一次的问题和回答。但这是第一次回答,所以主要根据用户提供的引用。 因此,回答如下:</think>### Python 读取 PDF 文件内容的方法 Python 提供了多种库来读取 PDF 文件内容,以下是三种常用方法及其实现步骤: --- #### 方法 1:使用 **PyPDF2**(基础文本提取) ```python import PyPDF2 # 打开 PDF 文件 with open('your_file.pdf', 'rb') as pdf_file: pdf_reader = PyPDF2.PdfFileReader(pdf_file) # 获取总页数 print(f"总页数: {pdf_reader.numPages}") # 逐页提取文本 for page_num in range(pdf_reader.numPages): page = pdf_reader.getPage(page_num) text = page.extractText() print(f"第 {page_num+1} 页内容:\n{text}\n") ``` **特点**: - 纯 Python 实现,轻量级 - 对简单文本提取有效,但复杂格式可能丢失排版信息[^1] - 不支持图片提取 --- #### 方法 2:使用 **Spire.PDF**(高级文本/图片提取) ```python from spire.pdf import PdfDocument # 加载 PDF doc = PdfDocument() doc.LoadFromFile("your_file.pdf") # 提取所有文本 all_text = [] for page in doc.Pages: text = page.ExtractText() # 提取文本 all_text.append(text) # 提取图片(需额外处理) images = page.ExtractImages() for img in images: img.Save(f"page{page.PageIndex}_img.png") print("".join(all_text)) doc.Close() ``` **特点**: - 支持文本、图片、表格提取 - 可处理加密文档 - 需安装:`pip install Spire.PDF`(免费版有水印和页数限制)[^2] --- #### 方法 3:使用 **pdfplumber**(精准文本定位) ```python import pdfplumber with pdfplumber.open('your_file.pdf') as pdf: for page in pdf.pages: # 提取完整文本 print(page.extract_text()) # 提取表格数据(示例) tables = page.extract_tables() for table in tables: print("检测到表格:", table) ``` **特点**: - 精准保持文本位置和表格结构 - 支持可视化调试(`page.to_image().debug_tablefinder()`) - 安装:`pip install pdfplumber` --- ### 选择建议 | 场景 | 推荐库 | |---------------------|---------------| | 快速提取简单文本 | PyPDF2 | | 需要图片/表格提取 | Spire.PDF | | 精确还原排版和表格 | pdfplumber | > ⚠️ 注意:所有 PDF 文本提取都可能因文件格式(扫描件/加密/特殊字体)失效,扫描件需先用 OCR 工具处理。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值