ai
  • index
  • cursor
  • vector
  • crawl
  • crawl-front
  • DrissionPage
  • logging
  • mysql
  • pprint
  • sqlalchemy
  • contextmanager
  • dotenv
  • Flask
  • python
  • job
  • pdfplumber
  • python-docx
  • redbook
  • douyin
  • ffmpeg
  • json
  • numpy
  • opencv-python
  • pypinyin
  • re
  • requests
  • subprocess
  • time
  • uuid
  • watermark
  • milvus
  • pymilvus
  • search
  • Blueprint
  • flash
  • Jinja2
  • secure_filename
  • url_for
  • Werkzeug
  • chroma
  • HNSW
  • pillow
  • pandas
  • beautifulsoup4
  • langchain-community
  • langchain-core
  • langchain
  • langchain_unstructured
  • libreoffice
  • lxml
  • openpyxl
  • pymupdf
  • python-pptx
  • RAGFlow
  • tabulate
  • sentence_transformers
  • jsonl
  • collections
  • jieba
  • rag_optimize
  • rag
  • rank_bm25
  • Hugging_Face
  • modelscope
  • all-MiniLM-L6-v2
  • ollama
  • rag_measure
  • ragas
  • ASGI
  • FastAPI
  • FastChat
  • Jupyter
  • PyTorch
  • serper
  • uvicorn
  • markdownify
  • NormalizedLevenshtein
  • raq-action
  • CrossEncoder
  • Bi-Encoder
  • neo4j
  • neo4j4python
  • matplotlib
  • Plotly
  • Streamlit
  • py2neo
  • abc
  • read_csv
  • neo4jinstall
  • APOC
  • neo4jproject
  • uv
  • GDS
  • heapq
  • 主要特点
  • 基本用法
    • 安装
    • 打开PDF文件
    • 提取文本
    • 提取表格
  • 高级功能
    • 表格提取设置
    • 可视化调试
    • 获取字符级信息
  • 与其他库的比较
  • 实际应用示例
    • 提取发票数据
    • 批量处理多个PDF
  • 性能优化技巧
  • 常见问题解决

pdfplumber 是一个 Python 库,专门用于从 PDF 文件中提取文本和表格数据。相比其他 PDF 处理库,它提供了更精确的页面元素定位和更灵活的提取选项。

主要特点 #

  1. 精确的文本提取:保留原始布局和位置信息
  2. 表格提取功能:能识别复杂表格结构
  3. 可视化调试:可以绘制提取的文本和表格边界
  4. 页面分析:获取字符、线、矩形等底层PDF元素

基本用法 #

安装 #

pip install pdfplumber

打开PDF文件 #

import pdfplumber

with pdfplumber.open("example.pdf") as pdf:
    # 处理PDF内容
    pass

提取文本 #

# 提取单页文本
with pdfplumber.open("example.pdf") as pdf:
    first_page = pdf.pages[0]
    text = first_page.extract_text()
    print(text)

# 提取所有页文本
with pdfplumber.open("example.pdf") as pdf:
    all_text = ""
    for page in pdf.pages:
        all_text += page.extract_text()
    print(all_text)

提取表格 #

with pdfplumber.open("example.pdf") as pdf:
    first_page = pdf.pages[0]
    table = first_page.extract_table()

    # 表格以二维列表形式返回
    for row in table:
        print(row)

高级功能 #

表格提取设置 #

table_settings = {
    "vertical_strategy": "text",  # 或"lines", "explicit"
    "horizontal_strategy": "text",
    "intersection_y_tolerance": 10,
}

with pdfplumber.open("example.pdf") as pdf:
    page = pdf.pages[0]
    table = page.extract_table(table_settings)

可视化调试 #

with pdfplumber.open("example.pdf") as pdf:
    page = pdf.pages[0]

    # 绘制文本边界
    im = page.to_image()
    im.debug_tablefinder().show()

    # 绘制线条
    im.reset().draw_lines(page.lines).show()

获取字符级信息 #

with pdfplumber.open("example.pdf") as pdf:
    page = pdf.pages[0]

    for char in page.chars:
        print(f"字符: {char['text']}, 位置: ({char['x0']}, {char['top']})")

与其他库的比较 #

特性 pdfplumber PyPDF2 pdfminer.six camelot
文本提取 ✓ ✓ ✓ ✓
表格提取 ✓ ✗ ✗ ✓
保留布局 ✓ ✗ ✓ ✓
可视化调试 ✓ ✗ ✗ ✓
性能 中等 快 慢 慢

实际应用示例 #

提取发票数据 #

with pdfplumber.open("invoice.pdf") as pdf:
    first_page = pdf.pages[0]

    # 查找"总计"后的金额
    words = first_page.extract_words()
    for i, word in enumerate(words):
        if word["text"] == "总计":
            total = words[i+1]["text"]
            print(f"发票总计金额: {total}")
            break

批量处理多个PDF #

import os
import pandas as pd

results = []

for filename in os.listdir("pdfs"):
    if filename.endswith(".pdf"):
        with pdfplumber.open(f"pdfs/{filename}") as pdf:
            first_page = pdf.pages[0]
            text = first_page.extract_text()
            results.append({"filename": filename, "content": text})

df = pd.DataFrame(results)
df.to_csv("pdf_contents.csv", index=False)

性能优化技巧 #

  1. 限制处理页数:只处理需要的页面
  2. 使用缓存:对重复处理的PDF缓存结果
  3. 并行处理:对多个PDF使用多进程
  4. 调整提取策略:根据PDF特点选择合适的表格提取策略

常见问题解决 #

  1. 表格提取不准确:

    • 尝试不同的提取策略
    • 调整容差参数
    • 先用可视化调试查看识别情况
  2. 文本顺序错乱:

    • 使用extract_text(x_tolerance=3, y_tolerance=3)调整容差
    • 按字符位置手动排序
  3. 内存不足:

    • 逐页处理而不是加载整个PDF
    • 使用pdfplumber.open(..., laparams={"line_overlap": 0.7})减少分析强度

pdfplumber 是处理PDF文本和表格数据的强大工具,特别适合需要精确提取结构化数据的场景。

访问验证

请输入访问令牌

Token不正确,请重新输入