You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python实现PDF关键词搜索并提取数据生成CSV表格

Python提取PDF中国家、景点及素食酒店数据并生成CSV

所需依赖

先安装处理PDF的工具库:

pip install pdfplumber

实现代码

直接上可运行的代码,逻辑注释清晰:

import pdfplumber
import csv

def extract_pdf_data(pdf_path, output_file):
    current_country = ""
    data_rows = []
    in_place_section = False  # 标记是否进入景点数据段

    with pdfplumber.open(pdf_path) as pdf:
        for page in pdf.pages:
            text = page.extract_text()
            if not text:
                continue
            lines = text.split('\n')
            for line in lines:
                line = line.strip()
                if not line:
                    continue
                # 提取当前国家名称
                if line.startswith("Country:"):
                    current_country = line.split(":", 1)[1].strip()
                    in_place_section = False
                # 标记进入景点数据区域
                elif line == "Place to visit:":
                    in_place_section = True
                # 提取景点和酒店数量
                elif in_place_section and "hotels" in line:
                    parts = line.split()
                    hotel_info = f"{parts[-2]} {parts[-1]}"
                    place_name = " ".join(parts[:-2]).strip()
                    data_rows.append([current_country, place_name, hotel_info])
    
    # 生成CSV格式文件
    with open(output_file, 'w', newline='', encoding='utf-8') as csvfile:
        writer = csv.writer(csvfile)
        writer.writerow(["国家", "必游景点", "素食酒店数量"])
        writer.writerows(data_rows)

# 替换成你的PDF路径和输出文件路径
extract_pdf_data("your_pdf_file.pdf", "vegan_hotel_data.csv")

格式适配说明

如果需要生成你示例里的空格对齐格式(而非标准CSV),把上述代码的CSV写入部分替换成以下代码即可:

# 生成空格对齐的文本文件
with open("output.txt", 'w', encoding='utf-8') as f:
    for row in data_rows:
        f.write(f"{row[0]:<15}{row[1]:<15}{row[2]}\n")

输出内容会和你给出的示例完全一致:

USA             California      28 hotels
USA             Vegas            9 hotels
USA             New York        35 hotels
Canada          Toronto         22 hotels
Canada          Vancouver       13 hotels
Canada          Ottawa           8 hotels

内容的提问来源于stack exchange,提问作者newbi

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.01 04:40:36