python:xml.etree,用 xmltodict 转换为json数据,生成jstree所需的文件

请参阅:java : pdfbox 读取 PDF文件内书签 或者 python:从PDF中提取目录

请注意:书的目录.txt 编码:UTF-8,推荐用 Notepad++ 转换编码。

xml 是 python 标准库,在 D:\Python39\Lib\xml\etree

pip install xmltodict ;

python 用 xml.etree.ElementTree,用 xmltodict 转换为json数据,jinja2 生成jstree模板所需的文件。

编写 txt_xml_etree_json.py  如下

# -*- coding: utf-8 -*-
""" 读目录.txt文件,用 xmltodict转换为json数据,生成jstree所需的文件 """
import os
import sys
import codecs
import json
import xml.etree.ElementTree as et
import xmltodict
from jinja2 import Environment,FileSystemLoader

if len(sys.argv) ==2:
    f1 = sys.argv[1]
else:
    print('usage: python txt_xml_etree_json.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)

fp = codecs.open(f1, mode="r", encoding="utf-8")
# 读取第一行:书名
title = fp.readline()
# 创建主题节点
root = et.Element("node")
root.set("id", '1')
root.set("text", title.strip())

# 定义状态:
state = et.SubElement(root, "state")
state.set("opened", 'true')
state.set("disabled", 'true')

# 用缩排表现层级关系,假设最多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, "children")
        node1.set("id", str(n))
        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, "children")
        else: node2 = et.SubElement(node1, "children")
        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, "children")
        else: node3 = et.SubElement(node2, "children")
        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, "children")
        else: node4 = et.SubElement(node3, "children")
        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, "children")
        else: node5 = et.SubElement(node4, "children")
        node5.set("id", str(n))
        node5.set("text", txt)
    else:
        print(txt)
    n += 1
fp.close()
print(f"line number: {n}")

# 转换成 str,方便导出
root_bytes = et.tostring(root, encoding="utf-8")
xml_str = root_bytes.decode()
try:
    json_dict = xmltodict.parse(xml_str, encoding='utf-8')
    json_str = json.dumps(json_dict['node'], indent=2)
except:
    print("xmltodict.parse error!")
# 去掉'@'
json_str = '['+ json_str.replace('\"@','"') +']'
#print(json_str)

# 使用 jinja2 对html模板文件进行数据替换
env = Environment(loader=FileSystemLoader('d:/python/'))
tpl = env.get_template('jstree_template.htm')
# 导出.html文件
f2 = fn +'.htm'
with codecs.open(f2, 'w', encoding='utf8') as fp:
    content = tpl.render(title=title.strip(), mydir=json_str)
    fp.write(content)

https://gitee.com/ 搜索 jstree 下载
https://gitee.com/mirrors/jstree?_from=gitee_search
git clone https://gitee.com/mirrors/jstree.git

编写 jstree 模板文件:jstree_template.htm




  
  
  
  {{title}}
  
  
  


  
  

运行 python txt_xml_etree_json.py your_pdf_dir.txt

生成 your_pdf_dir.htm

你可能感兴趣的:(python,xml,etree,xmltodict,jinja2,python)