当前位置: 首页 > news >正文

python:PyPDF2 从PDF文件中提取目录

我发现 pypdf  和 pypdf2 的作者是同一人:Mathieu Fenniak 

pip install pypdf2 ;

  pypdf2-3.0.1-py3-none-any.whl (232 kB)

编写 pdf_read_dir.py  如下

# -*- coding: utf-8 -*-
""" pypdf2==3.0.1 从PDF中提取目录 """
import os
import sys
from PyPDF2 import PdfReader#每个书签的索引格式
#{'/Title': '书签名', '/Page': '指向的目标页数', '/Type': '类型'}# 查找指定的字符出现次数
def find_char(str1, char):cs = 0for c in str1:if c == char:cs += 1return csdirectory_str = ''
def bookmark_listhandler(list):global directory_strfor message in list:if isinstance(message, dict):title = message['/Title'].strip()if title.startswith("Chapter"): directory_str += '\n' + title + '\n'elif title[0:2] in ("序章","前言") or title.startswith("序"):directory_str += '\n' + title + '\n'elif title.startswith("第") and title.split()[0][-1] =="章":directory_str += '\n' + title + '\n'elif title.startswith("第") and title.split()[0][-1] =="节":directory_str += '  ' + title + '\n'elif title.startswith("第"):directory_str += '\n' + title + '\n'elif title[0] in ('一','二','三','四','五','六','七','八','九','十'):directory_str += '    ' + title + '\n'elif title[0] in "1234567890":cs = find_char(title, '.')directory_str += '  '*cs + title + '\n'else:directory_str += '        ' + title + '\n'else:bookmark_listhandler(message)# main()
if len(sys.argv) ==2:file1 = sys.argv[1]
else:print('usage: python pdf_read_dir.py file.pdf')sys.exit(1)if not os.path.exists(file1):print(f"{file1} is not exists.")sys.exit(2)    fn,ext = os.path.splitext(file1)
if ext.lower() != '.pdf':print("Please specify a valid pdf file")sys.exit(3)with open(file1, 'rb') as f1:pdf = PdfReader(f1)# 检索文档中存在的文本大纲,返回的对象是一个嵌套的列表bookmark_listhandler(pdf.outline)if len(directory_str) >0:fname = fn.split('\\')[-1]file2 = fn + '.txt'with open(file2, 'w', encoding='utf-8') as fp:fp.write(fname +'\n')fp.write(directory_str)
else:print("it no directory.")

运行 python pdf_read_dir.py your_ebook.pdf

生成  your_ebook.txt 

由于算法优劣原因,生成的结果正确性始终比不过 java : pdfbox 读取 PDF文件内书签

http://www.lryc.cn/news/301328.html

相关文章:

  • Java 2:运算符、表达式和语句
  • 批量提取word文件中文本框内容的三种方法
  • Leecode之合并两个有序链表
  • 陶建国教授谈中西方文化的差异与交融
  • Ps:画笔选项
  • 嵌入式——Flash(W25Q64)
  • stm32:pwm output模块,记录一下我是用smt32,输出pwm波的记录--(实现--重要)
  • phpstrom创建thinkphp项目
  • 【Linux】线程同步
  • 如何在多头自注意力机制的交叉学习中引入对于物理、生理、心理世界客观规律的对照验证...
  • 智慧公厕:让智慧城市的公共厕所焕发“智慧活力”
  • vue导出word文档(图文示例)
  • 【C Primer Plus第六版 学习笔记】 第十七章 高级数据表示
  • 租用一个服务器需要多少钱?2024阿里云新版报价
  • python-产品篇-游戏-成语填填乐
  • 数据库数据加密的 4 种常见思路的对比
  • HCIA-HarmonyOS设备开发认证V2.0-IOT硬件子系统-PWM
  • 001kafka源码项目gradle报错UnsupportedClassVersionError-kafka-报错-大数据学习
  • 单片机学习笔记---直流电机驱动(PWM)
  • Scrum敏捷培训机构推荐
  • 《Go 简易速速上手小册》第5章:并发编程(2024 最新版)
  • python - 模块
  • 【Web】CTFSHOW java刷题记录(全)
  • 全球付汇业务的流程
  • ubuntu22.04@laptop OpenCV Get Started: 012_mouse_and_trackbar
  • 信息安全性测试
  • [HTML]Web前端开发技术26(HTML5、CSS3、JavaScript )JavaScript基础——喵喵画网页
  • 【Java】文件操作与IO
  • 开关电源电路主要元器件基础知识详解
  • - 项目落地 - 《选择项目工具的方法论》