pdf合并(python)

工具代码,背景是某门课的ppt章节分类得过于详细,比如1.01,然后一份pdf文件只有几页,故借助PyPDF2进行pdf文件合并。

python 复制代码
import os
import copy
from PyPDF2 import PdfMerger

target_path = 'D:\\study\\大四上\\生物信息\\ppt'
pdf_lst = [f for f in os.listdir(target_path) if f.endswith('.pdf')]

classified_lst = []
t = []
prefix = None
for filename in pdf_lst:
    if not filename[0].isdigit():
        continue
    if prefix is None or filename[0] == prefix:
        prefix = filename[0]
    else:
        prefix = filename[0]
        classified_lst.append(copy.deepcopy(t))     # 深浅拷贝问题
        t.clear()
    t.append(filename)
classified_lst.append(t)

fclassified_lst = []
for x in classified_lst:
    t = []
    for y in x:
        t.append(os.path.join(target_path, y))
    fclassified_lst.append(t)

# 将相同的章节合并到一个pdf中
num = 1
file_merger = PdfMerger()
for chapter in fclassified_lst:
    for pdf in chapter:
        file_merger.append(pdf)
    file_merger.write(target_path + "\\sum\\chapter" + str(num) + ".pdf")
    num += 1
    file_merger = PdfMerger()

print("done!")
相关推荐
markfeng82 小时前
Python+Django+H5+MySQL项目搭建
python·django
GinoWi2 小时前
Chapter 2 - Python中的变量和简单的数据类型
python
JordanHaidee2 小时前
Python 中 `if x:` 到底在判断什么?
后端·python
ServBay3 小时前
10分钟彻底终结冗长代码,Python f-string 让你重获编程自由
后端·python
闲云一鹤3 小时前
Python 入门(二)- 使用 FastAPI 快速生成后端 API 接口
python·fastapi
Rockbean4 小时前
用40行代码搭建自己的无服务器OCR
服务器·python·deepseek
曲幽5 小时前
FastAPI + Ollama 实战:搭一个能查天气的AI助手
python·ai·lora·torch·fastapi·web·model·ollama·weatherapi
用户60648767188966 小时前
国内开发者如何接入 Claude API?中转站方案实战指南(Python/Node.js 完整示例)
人工智能·python·api
只与明月听6 小时前
RAG深入学习之Chunk
前端·人工智能·python
用户8356290780517 小时前
自动化文档处理:Python 批量提取 PDF 图片
后端·python