tree_common.py 2.4 KB
Newer Older
L
luxin 已提交
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77
#!/usr/bin/env python
# -*- encoding: utf-8 -*-
'''
@File    :   tree_common.py
@Time    :   2022/01/20 18:17:41
@Author  :   Lu Xin 
@Contact :   luxin@csdn.net
'''

# here put the import lib
import os
import ipdb
from tqdm import tqdm
from treelib import Tree
from treelib import Node


class TreeCommon:
    def __init__(self):
        pass

    def load(self):
        pass

    @classmethod
    def construct_tree(cls, tree : Tree, tree_dict, parent):
        # tree_name = list(tree_dict.keys())[0]
        # root_node = Node(
        #     tag="tree_name", 
        #     identifier=tree_dict[tree_name]["node_id"], 
        #     data={
        #         "keywords": tree_dict[tree_name]["keywords"],
        #         "keywords_must": tree_dict[tree_name]["keywords_must"],
        #         "keywords_forbid": tree_dict[tree_name]["keywords_forbid"]
        # })
        # tree.add_node(root_node, parent=None)

        for node_text, node_info in tree_dict.items():
            node_id = node_info["node_id"]
            node_kw = node_info["keywords"]
            node_kw_must = node_info["keywords_must"]
            node_kw_forbid = node_info["keywords_forbid"]
            subtree_list = node_info["children"]
            node = Node(
                tag=node_text, 
                identifier=node_id, 
                data={
                    "keywords": node_kw,
                    "keywords_must": node_kw_must,
                    "keywords_forbid": node_kw_forbid
                })
            tree.add_node(node, parent=parent)
            for subtree_dict in subtree_list:
                cls.construct_tree(tree, subtree_dict, node_id)

    @classmethod
    def get_tree_json_recursively(cls, tree : Tree, cur_node_id):
        struct = {}

        cur_node = tree.get_node(cur_node_id)
        cur_node_text = cur_node.tag

        struct[cur_node_text] = {
            "keywords": cur_node.data["keywords"],
            "keywords_must": cur_node.data["keywords_must"],
            "keywords_forbid": cur_node.data["keywords_forbid"],
            "children": [],
            "node_id": cur_node_id
        }

        all_children_list = [m_node.identifier for m_node in tree.children(cur_node_id)]

        for child_node in all_children_list:
            child_struct = cls.get_tree_json_recursively(tree, child_node)
            struct[cur_node_text]["children"].append(child_struct)

        return struct