使用PDF抽取电子书目录
阅读电子书时,想着在自己认为关键的地方记一些笔记,随着阅读的深入,书中出彩的部分越来越多,笔记也越记越多,有时会忘记看此书的初衷。
那么有没有方便快捷的方法提取电子书大纲,在读书的时候打个书签,读完之后导出自己的书签,就自动生成一份阅读笔记,岂不美哉。
在此需要重点提示的是: 有些书可能辈子只有一次阅读的机会(就像某些人一辈子只会遇见一次),总是幻想着还有下次机会的方法是不可取的。正确的做法是,第一次读时就当是最后一次读,用心记住重要的知识点。
python提取pdf目录的步骤
一、安装所需的库
pip install PyPDF2
二、使用代码提取目录
这里对抽出的目录进行了加工,以markdown形式的写入到文件
import PyPDF2
def extract_pdf_table_of_contents(pdf_path):
with open(pdf_path, 'rb') as file:
pdf_reader = PyPDF2.PdfReader(file)
if pdf_reader.outline:
return pdf_reader.outline
else:
return None
res = []
def extract_table_content(table_of_contents, sep="#", count=1):
global res
if table_of_contents:
for item in table_of_contents:
if isinstance(item, list):
res.append(extract_table_content(item, sep="#", count=count + 1))
else:
res.append(sep * count +' '+ item.title.replace("\r", ""))
if __name__ == '__main__':
pdf_file = "D:\win10\Downloads\1.pdf"
# extract_pdf_table_of_contents()
pdf_reader = extract_pdf_table_of_contents(pdf_file)
extract_table_content(pdf_reader)
result_md = open("1.md", 'w+',encoding='utf-8')
for s in res:
if s:
result_md.write(s)
result_md.write("\r\n")
result_md.flush()