删除页头
E:\Microsoft VS Code\py\2024年9月21日-读取PDF.py
环境变量 --> vscode-python312 * X:\CondaEnvs\vscode-python312
import PyPDF2
import re
# 指定PDF文件路径
pdf_path = r'S:\temp\vk\China After Mao_rearranged4-5.pdf'
output_path = r'S:\temp\vk\output.txt' # 输出文本文件路径
def extract_text_without_headers_footers(pdf_path):
# 打开PDF文件
with open(pdf_path, 'rb') as file:
pdf_reader = PyPDF2.PdfReader(file)
# 获取PDF页数
num_pages = len(pdf_reader.pages)
print(f"PDF文件共有 {num_pages} 页")
# 用于保存所有页面的文本
all_text = []
for page_num in range(num_pages):
page = pdf_reader.pages[page_num]
text = page.extract_text()
if text: # 确保提取到文本
# 假设每页的前3行是页头,后3行是页脚
lines = text.split('\n')
# 排除前3行和后3行
body_text = lines[1:] if len(lines) > 6 else lines
# 将文本合并为单一字符串
page_text = "\n".join(body_text)
# 使用正则表达式删除特定文本
page_text = re.sub(r'中文版導言\s*\d+', '', page_text)
all_text.append(page_text)
# 将所有页面的文本写入输出文件
with open(output_path, 'w', encoding='utf-8') as output_file:
for i, text in enumerate(all_text):
output_file.write(f"\n{text}\n\n")
print(f"处理后的文本已保存到: {output_path}")
extract_text_without_headers_footers(pdf_path)