Python功能实现:为pdf电子书籍生成书签目录

      今天搞了本pdf电子书看,奈何没有书签目录,用acrobat DC看起来很难受,所以索性写了个python脚本,配合PdfEditor软件能够较为方便地生成可跳转页码的书签目录。

注意:

1、用python3运行我提供的脚本。

2、请提前下载PdfEditor软件并了解如何用其制作书签目录。

3、脚本运行需要提供文件origin.txt文件,内容是书籍对应的原始书签目录。

4、实现思路主要使用了正则匹配,大家可以去了解下python re库的使用,正则规则最好根据origin.txt自行分析调整。

5、大家主要参考程序的实现思路,请根据实际情况进行修改。

脚本内容:

# 作者:Melody
# 功能:PDF书籍目录生成脚本,生成目标文件后需要配合PdfEditor软件使用
# 时间:2021/5/30
import re
pageOffset = 16 # 印刷链接页码与实际跳转页码偏移量
originFileName = 'origin.txt'
resultFileName = 'result.txt'

# 获得目标文件绝对路径
nameList = __file__.split('\\')
nameList.pop(-1) # 去除脚本文件名
nameList.append(originFileName)
path = "//".join(nameList)
f = open(path, 'r', encoding='utf-8')
info = f.read()
f.close()
myList = list()

# 找到无效小数点对应区间
cmd = r'[^\.]\.{2,}(\d| )'
for match in re.finditer(cmd, info):
	myList.append((match.start()+1, match.end()-2))

# 删除无效的小数点
start = 0
end = myList[0][0]
newInfo = ""
cnt = 0
for i in range(len(myList)): 
	if cnt != 0:
		end = myList[i][0]
		newInfo += info[start+1:end] + "\t"
	else:
		newInfo += info[start:end] + "\t"
	start = myList[i][1]
	cnt += 1

# 给页码加偏移
splitForPage = newInfo.split('\n') 
newInfo = ""
for item in splitForPage:
	temp = item.split('\t')
	try:
		num = int(temp[-1]) + pageOffset
		temp[-1] = "\t" + str(num)
	except(ValueError):
		pass
	item = "".join(temp)
	newInfo += item + "\n" 

# 删除目录无效章节
splitForDelete = newInfo.split('\n') 
newInfo = ""
for item in splitForDelete:
	if item != "":
		if item[0] == "测" or item[0] == "例":
			continue
		else:
			newInfo += item + "\n"
	else:
		continue

# 给章节加缩进,根据小数点个数判断章节层级
splitForCap = newInfo.split('\n') 
newInfo = ""
for item in splitForCap:
	temp = item.split(" ")
	capter = temp[0]
	numPoint = capter.count(".")
	if numPoint == 1:
		item = '\t' + item
	if numPoint == 2:
		item = "\t\t" + item
	newInfo += item + "\n"

nameList.pop(-1)
nameList.append(resultFileName)
path = "//".join(nameList)
f = open(path, 'w', encoding='utf-8')
f.write(newInfo)
f.close()

运行结果:

origin.txt内容:(自己想办法搞到这些信息,我是直接从pdf里复制粘贴的)

result.txt:

用PdfEditor打开目标pdf,将result.txt内容复制到软件里,直接保存就好了!太强了这软件!

正则表达式学习网站:

https://regex101.com/r/dmRygT/1

https://github.com/ziishaned/learn-regex/blob/master/translations/README-cn.md

  • 0
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 3
    评论
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值