python:lxml 读目录.txt文件,用 xmltodict 转换为json数据,生成jstree所需的文件

请参阅:java : pdfbox 读取 PDF文件内书签

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

pip install lxml ; 

lxml-5.1.0-cp310-cp310-win_amd64.whl (3.9 MB)

pip install xmltodict ;

lxml 读目录.txt文件,用 xmltodict 转换为 json数据,生成 jstree模板所需的文件。

编写 txt_etree_json.py  如下

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

if len( sys.argv ) ==2:
    f1 = sys.argv[1]
else:
    print('usage: python txt_etree_mm.py file1.txt')
    sys.exit(1)

if not os.path.exists(f1):
    print("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 = etree.Element("node")
root.set("id", '1')
root.set("text", title.strip())

# 定义状态:
state = etree.Element("state")
state.set("opened", 'true')
state.set("disabled", 'true')
root.append(state)
# 用缩排表现层级关系,假设最多5个层级
indent1 = ' '*2
indent2 = ' '*4
indent3 = ' '*6
indent4 = ' '*8

n = 2
for line in fp:
    txt = line.strip()
    txt = txt[0:-3] # 去掉行尾的页数
    if len(txt) ==0:
        continue
    elif len(txt) >0 and line[0] !=' ':
        # 创建主题的子节点(1级节点)
        node1 = etree.Element("children")
        node1.set("id", str(n))
        node1.set("text", txt)
        root.append(node1)
        p_node = node1 # 寄存父节点
    elif line.startswith(indent1) and line[2] !=' ':
        # 创建node1的子节点(2级节点)
        node2 = etree.Element("children")
        node2.set("id", str(n))
        node2.set("text", txt)
        try: type(node1)
        except NameError: root.append(node2)
        else: node1.append(node2)
        p_node = node2
    elif line.startswith(indent2) and line[4] !=' ':
        # 创建node2的子节点(3级节点)
        node3 = etree.Element("children")
        node3.set("id", str(n))
        node3.set("text", txt)
        try: type(node2)
        except NameError: node1.append(node3)
        else: node2.append(node3)
        p_node = node3
    elif line.startswith(indent3) and line[6] !=' ':
        # 创建node3的子节点(4级节点)
        node4 = etree.Element("children")
        node4.set("id", str(n))
        node4.set("text", txt)
        try: type(node3) 
        except NameError: node2.append(node4)
        else: node3.append(node4)
        p_node = node4
    elif line.startswith(indent4) and line[8] !=' ':
        # 创建node4的子节点(5级节点)
        node5 = etree.Element("children")
        node5.set("id", str(n))
        node5.set("text", txt)
        try: type(node4) 
        except NameError: p_node.append(node5)
        else: node4.append(node5)
    else:
        print(txt)
    n += 1
fp.close()
print(f"line number: {n}")

# 转换成 str,方便导出
root_bytes = etree.tostring(root, pretty_print=False)
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 +'.html'
with codecs.open(f2, 'w', encoding='utf8') as fp:
    content = tpl.render(title=title.strip(), mydir=json_str)
    fp.write(content)

Gitee - 基于 Git 的代码托管和研发协作平台 搜索 jstree 后下载

编写 jstree 模板文件:jstree_template.htm




  
  
  
  {{title}}
  
  
  


  
  

运行 python txt_etree_json.py your_pdf_dir.txt

生成 your_pdf_dir.html

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