如何使用 treelib 加载已保存的 JSON 树?

How can I load a saved JSON tree with treelib?

我制作了一个 Python 脚本,其中我使用 BeautifulSoup 处理一个大的 html,同时使用 treelib 从它构建树:http://xiaming.me/treelib/。 我发现这个库带有在我的系统上保存树文件并将其解析为 JSON 的方法。但是在我这样做之后,我该如何加载它呢? 为每个 运行 构建相同的整棵树效率不高。我想我可以创建一个函数来解析之前写入文件的 JSON 树,但我只想确定是否存在另一种简单的方法。

提前致谢

简单的答案

使用这个 treelib,你不能

正如他们在文档中所说的那样 (http://xiaming.me/treelib/pyapi.html#node-objects):

tree.save2file(filename[, nid[, level[, idhidden[, filter[, key[, reverse]]]]]]])
    Save the tree into file for offline analysis.

它不包含任何JSON-Parser,因此无法读取文件。

你能做什么?

您别无选择,只能为每个 运行 每次构建树。

实施 JSON-Reader 来解析文件并为您创建树。

https://docs.python.org/2/library/json.html

我为我的案例构建了一个小型解析器。也许它适用于你的情况。 笔记标识符以标签加上节点在树中的深度(标签+深度)命名。

import json
from types import prepare_class
from treelib import Node, Tree, node
import os

file_path = os.path.abspath(os.path.dirname(__file__))

with open(file_path + '\tree.json') as f:
    tree_json = json.load(f)

tree = Tree()

def load_tree(json_tree, depth=0, parent=None):
    k, value = list(json_tree.items())[0]
    
    if parent is None:
        tree.create_node(tag=str(k), identifier=str(k)+str(depth))
        parent = tree.get_node(str(k)+str(depth))

    for counter,value in enumerate(json_tree[k]['children']):    
        if isinstance(json_tree[k]['children'][counter], str):
            tree.create_node(tag=value, identifier=value+str(depth), parent=parent)
        else:
            tree.create_node(tag=list(value)[0], identifier=list(value)[0]+str(depth), parent=parent)
            load_tree(json_tree[k]['children'][counter], depth+1, tree.get_node(list(value)[0]+str(depth)) )

load_tree(tree_json)