赞
踩
- import os
- import pandas as pd
- import pdfplumber
- import re
-
- # 设置 PDF 文件夹路径
- pdf_folder_path = r"C:\Users\win10\Desktop\pdf_files"
-
- # 读取原始 Excel 文件并获取 pdf_filename 列
- df = pd.read_excel(r'C:\Users\win10\Desktop\工作簿2.xlsx')
- pdf_filenames = df["pdf_filename"].tolist()
-
- # 创建空列表用于存储结果
- conclusion_pages = []
-
- # 遍历每个 PDF 文件并提取符合条件的文本
- for filename in pdf_filenames:
- # 拼接 PDF 文件的完整路径
- pdf_path = os.path.join(pdf_folder_path, filename)
-
- # 清空 conclusion_pages 列表,以便处理下一个 PDF 文件
- conclusion_pages.clear()
-
- with pdfplumber.open(pdf_path) as pdf:
- # 遍历每一页
- for page_num, page in enumerate(pdf.pages, start=1):
- if page_num < 15:
- continue
-
- # 获取当前页的全部文本内容
- text = page.extract_text()
-
- # 提取包含关键字的部分文本
- conclusion_text = re.search(r"\bConclusion\b", text)
- summary_text = re.search(r"\bSummary\b", text)
-
- if conclusion_text and summary_text:
- # 找到关键字所在行,并获取该行内容
- conclusion_line = text[conclusion_text.start():].split("\n", maxsplit=1)[0]
- conclusion_page_text = conclusion_line + "\n"
-
- # 从关键字所在行开始往下逐行提取文本,直到遇到空行为止
- for line in text[conclusion_text.end():].split("\n"):
- line = line.strip()
-
- # 判断该行是否为页码,如果是则跳过
- if re.match(r"^\d+\s*$", line):
- continue
-
- if not line:
- break
- conclusion_page_text += line + "\n"
-
- summary_line = text[summary_text.start():].split("\n", maxsplit=1)[0]
- summary_page_text = summary_line + "\n"
-
- # 从关键字所在行开始往下逐行提取文本,直到遇到空行为止
- for line in text[summary_text.end():].split("\n"):
- line = line.strip()
-
- # 判断该行是否为页码,如果是则跳过
- if re.match(r"^\d+\s*$", line):
- continue
-
- if not line:
- break
- summary_page_text += line + "\n"
-
- # 将包含关键字的完整页文本添加到列表中
- conclusion_pages.append(conclusion_page_text + "\n\n" + summary_page_text)
-
- # 将列表中的结果添加到原始 Excel 中的 "conclusion_page" 列
- df.loc[df['pdf_filename'] == filename, "conclusion_text"] = "\n\n".join(conclusion_pages)
-
- # 将结果保存到新的 Excel 文件中
- df.to_excel(r'C:\Users\win10\Desktop\工作簿3.xlsx', index=False)
特别是提取 "Conclusion" 和 "summary" 部分的逻辑封装成函数并复用,让代码的可读性更好,同时避免了重复代码的问题。
此外,你还把定义列表和清空列表操作移到了循环外部,避免了原来代码中可能会出现的问题,真正实现了对结果的正确处理。
用正则匹配去除了带有的页数。
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。