读取pdf中论文题目并修改标题

思路就是读取pdf第一页中
逐步便利寻找最大的字号
然后把所有是最大字号的句子找到合并为一句一般就是标题了

但是遇到期刊名比标题名字号大的就蛋疼了
欢迎交流!

import os
import PyPDF2

import fitz

def find_largest_font_sentence(pdf_path):
    largest_font_size = 0
    largest_font_sentence = ''
    maxsize=0
    # 打开PDF文件
    document = fitz.open(pdf_path)

    for page_number in range(document.page_count):
        page = document.load_page(page_number)
        blocks = page.get_text("dict")["blocks"]

        for block in blocks:
            if "lines" in block:  # 检查是否存在 lines 字段
                for line in block["lines"]:
                    for span in line["spans"]:
                        if span["size"] > largest_font_size:
                            largest_font_size = span["size"]
                            largest_font_sentence = span["text"]
        maxsize=largest_font_size
        for block in blocks:
            if "lines" in block:  # 检查是否存在 lines 字段
                for line in block["lines"]:
                    for span in line["spans"]:
                        if span["size"] ==maxsize:
                            if largest_font_sentence!=span["text"]:
                                largest_font_sentence = largest_font_sentence+' '+span["text"]

    return largest_font_sentence

# 用于测试的PDF文件路径



def rename_pdfs(directory):
    for filename in os.listdir(directory):
        if filename.endswith(".pdf"):
            filepath = os.path.join(directory, filename)
            filepath=filepath.strip()
            largest_font_sentence = find_largest_font_sentence(filepath)
            title=largest_font_sentence
            new_filename = title.strip() + ".pdf"
            new_filepath = os.path.join(directory, new_filename)
            os.rename(filepath, new_filepath)
            print(f"Renamed {filename} to {new_filename}")


# 指定包含英文论文PDF的目录路径
pdf_directory = "PDF所在的文件夹目录"


# 调用函数进行重命名
rename_pdfs(pdf_directory)

读取pdf中论文题目并修改标题_第1张图片
读取pdf中论文题目并修改标题_第2张图片

你可能感兴趣的:(python脚本,pdf)