PyCharm提取病案首页的“姓名”来重命名pdf文件

提取病案首页“姓名”操作步骤

任务要求

1.提取姓名: 提取病案首页的“姓名”,为2-4个汉字,位于姓名和性别之间。
2.重命名: 以该姓名来重命名pdf的文件名称。

image

import os
import re
import pdfplumber
from pathlib import Path

def extract_patient_name(pdf_path):
    """从PDF中提取患者姓名"""
    try:
        with pdfplumber.open(pdf_path) as pdf:
            first_page = pdf.pages[0]
            text = first_page.extract_text()
            
            # 优化正则表达式匹配"姓名"后的2-4个汉字
            name_match = re.search(r'姓名\s*([\u4e00-\u9fa5]{2,4})\s*性别', text)
            if name_match:
                return name_match.group(1).strip()
            
            # 备用匹配模式(针对不同格式)
            alt_match = re.search(r'姓名[::]\s*([\u4e00-\u9fa5]{2,4})', text)
            if alt_match:
                return alt_match.group(1).strip()
            
            print(f"警告:未在 {pdf_path.name} 中找到姓名格式")
            return None
            
    except Exception as e:
        print(f"读取 {pdf_path.name} 出错: {str(e)}")
        return None

def batch_rename_pdfs(pdf_dir):
    """批量重命名PDF文件"""
    pdf_dir = Path(pdf_dir)
    if not pdf_dir.exists():
        print(f"错误:目录不存在 {pdf_dir}")
        return
    
    print(f"开始处理目录: {pdf_dir}")
    total = 0
    success = 0
    
    for pdf_file in pdf_dir.glob("*.pdf"):
        total += 1
        try:
            patient_name = extract_patient_name(pdf_file)
            if not patient_name:
                print(f"跳过:无法从 {pdf_file.name} 提取姓名")
                continue
            
            # 构建新文件名(处理重名)
            new_name = f"{patient_name}.pdf"
            new_path = pdf_file.parent / new_name
            counter = 1
            
            while new_path.exists():
                new_name = f"{patient_name}_{counter}.pdf"
                new_path = pdf_file.parent / new_name
                counter += 1
            
            # 执行重命名
            pdf_file.rename(new_path)
            print(f"重命名: {pdf_file.name} → {new_name}")
            success += 1
            
        except Exception as e:
            print(f"处理 {pdf_file.name} 失败: {str(e)}")
    
    print(f"\n处理完成!成功 {success}/{total} 个文件")

if __name__ == "__main__":
    # 配置PDF目录路径
    target_dir = r"H:\H:\需提供佐证科室明细\神外二科四肢血管彩超\病案首页"
    
    # 执行批量重命名
    batch_rename_pdfs(target_dir)
    
    # 添加WPS预处理选项(如果需要)
    print("\n提示:如果有文件无法读取,可先用WPS批量重新保存PDF")