请参阅:java : pdfbox 读取 PDF文件内书签 或者 python:从PDF中提取目录
请注意:书的目录.txt 编码:UTF-8,推荐用 Notepad++ 转换编码。
xml 是 python 标准库,在 D:\Python39\Lib\xml\etree
python 用 xml.etree.ElementTree 生成思维导图 Freemind(.mm)文件
编辑 txt_xml_etree_mm.py 如下
python
# -*- coding: utf-8 -*-
""" 读目录.txt文件,使用 xml.etree 生成思维导图 Freemind(.mm)文件"""
import os
import sys
import codecs
import xml.etree.ElementTree as et
if len(sys.argv) ==2:
f1 = sys.argv[1]
else:
print('usage: txt_xml_etree_mm.py file1.txt')
sys.exit(1)
if not os.path.exists(f1):
print(f"ERROR: {f1} not found.")
sys.exit(1)
fn,ext = os.path.splitext(f1)
if ext.lower() != '.txt':
print('ext is not .txt')
sys.exit(2)
# 创建根节点
map1 = et.Element("map")
map1.set('version', '1.0.1')
fp = codecs.open(f1, mode="r", encoding="utf-8")
# 读取第一行:书名
title = fp.readline()
# 创建主题节点
root = et.SubElement(map1, "node")
root.set('ID', '1')
root.set('STYLE', 'bubble') # 泡框
root.set('TEXT', title.strip())
# 定义连线的颜色:红色
edge = et.SubElement(root, "edge")
edge.set('COLOR', "#ff0000")
# 用缩排表现层级关系,假设最多5个层级
indent1 = ' '*2
indent2 = ' '*4
indent3 = ' '*6
indent4 = ' '*8
n = 2
for line in fp:
txt = line.strip()
if len(txt) ==0:
continue
txt = txt[0:-3] # 去掉行尾的页数
if len(txt) >0 and line[0] !=' ':
# 创建主题的子节点(1级节点)
node1 = et.SubElement(root, "node")
node1.set('ID', str(n))
node1.set('POSITION', "right")
node1.set('TEXT', txt)
p_node = node1 # 寄存父节点
elif line.startswith(indent1) and line[2] !=' ':
# 创建node1的子节点(2级节点)
try: type(node1)
except NameError: node2 = et.SubElement(root, "node")
else: node2 = et.SubElement(node1, "node")
node2.set('ID', str(n))
node2.set('TEXT', txt)
p_node = node2
elif line.startswith(indent2) and line[4] !=' ':
# 创建node2的子节点(3级节点)
try: type(node2)
except NameError: node3 = et.SubElement(node1, "node")
else: node3 = et.SubElement(node2, "node")
node3.set('FLODED', "true")
node3.set('ID', str(n))
node3.set('TEXT', txt)
p_node = node3
elif line.startswith(indent3) and line[6] !=' ':
# 创建node3的子节点(4级节点)
try: type(node3)
except NameError: node4 = et.SubElement(node2, "node")
else: node4 = et.SubElement(node3, "node")
node4.set('ID', str(n))
node4.set('TEXT', txt)
p_node = node4
elif line.startswith(indent4) and line[8] !=' ':
# 创建node4的子节点(5级节点)
try: type(node4)
except NameError: node5 = et.SubElement(p_node, "node")
else: node5 = et.SubElement(node4, "node")
node5.set('ID', str(n))
node5.set('TEXT', txt)
else:
print(txt)
n += 1
fp.close()
# 转换成 str,方便导出
map_bytes = et.tostring(map1, encoding="utf-8")
# 导出到 .mm 格式的文件中
f2 = fn +'.mm'
with open(f2, 'w+b') as fp:
fp.write(map_bytes)
print(f"line number: {n}")
运行 python txt_xml_etree_mm.py your_pdf_dir.txt
生成 your_pdf_dir.mm