当前位置: 首页 > news >正文

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文件,xmltodict 转换为json数据,生成jstree所需的文件 """
import os
import sys
import codecs
import json
from lxml import etree
import xmltodict
from jinja2 import Environment,FileSystemLoaderif 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(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 = 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 = ' '*8n = 2
for line in fp:txt = line.strip()if len(txt) ==0:continuetxt = txt[0:-3] # 去掉行尾的页数if 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 = node2elif 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 = node3elif 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 = node4elif 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 后下载

https://gitee.com/mirrors/jstree?_from=gitee_search
git clone https://gitee.com/mirrors/jstree.git

编写 jstree 模板文件:jstree_template.htm

<!DOCTYPE html>
<html lang="en">
<head><meta charset="UTF-8"><meta http-equiv="X-UA-Compatible" content="IE=Edge"><meta name="viewport" content="width=device-width, initial-scale=1"><title>{{title}}</title><script src="../js/jquery-3.2.1.min.js"></script><link rel="stylesheet" href="../js/jstree/dist/themes/default/style.css" /><script src="../js/jstree/dist/jstree.min.js"></script>
</head>
<body><!-- 搜索框 --><div class="search_input"><input type="text" id="search_a" /><img src="../js/jstree/dist/search.png" /></div><div id="treeview1" class="treeview"></div>
<script type="text/javascript">var mydir = {{mydir}};$("#treeview1").jstree({'core' : {"multiple" : false,'data' : mydir,'dblclick_toggle': true},"plugins" : ["search"]});//输入框输入时自动搜索var tout = false;$('#search_a').keyup(function(){if (tout) clearTimeout(tout);    tout = setTimeout(function(){$('#treeview1').jstree(true).search($('#search_a').val());   }, 250);});   
</script> 
</body>
</html>

运行 python txt_etree_json.py your_pdf_dir.txt

生成 your_pdf_dir.html

http://www.lryc.cn/news/298168.html

相关文章:

  • 【Spring】Spring 对 Ioc 的实现
  • QT学习文件操作类 QFile
  • VOL_常用记录!!
  • 解决Typora导出HTML不显示图片
  • React Native开发iOS实战录
  • C++局部变量与全局变量
  • 深入理解ES的倒排索引
  • HTML世界之第一重天
  • docker run报 docker: Error response from daemon: no command specified.
  • vue3 之 商城项目—详情页
  • Linux笔记之Docker进行镜像备份与迁移
  • C#,欧拉常数(Euler Constant)的算法与源代码
  • asio监听eventfd
  • 《统计学简易速速上手小册》第9章:统计学在现代科技中的应用(2024 最新版)
  • 问题排查利器 - 分布式 trace
  • C++进阶(十四)智能指针
  • GPT最新进展:推出视频功能!迭代即将来临!
  • 各款Excel、word在线预览工具对比分析以及onlyoffice预览Excel加载时间长的解决方案
  • 【课程作业_01】国科大2023模式识别与机器学习实践作业
  • LeetCode374. Guess Number Higher or Lower——二分查找
  • 继承
  • 北斗卫星在物联网时代的应用探索
  • SQL注入 - 利用报错函数 floor 带回回显
  • NLP_Bag-Of-Words(词袋模型)
  • C语言rand随机数知识解析和猜数字小游戏
  • django中的缓存功能
  • 三、搜索与图论
  • 【翻译】Processing安卓模式的安装使用及打包发布(内含中文版截图)
  • MATLAB图像处理——边缘检测及图像分割算法
  • 探索设计模式:原型模式深入解析