Python的treelib构建多叉树——树剪枝

采用什么样的方式怎样剪枝,下面是按照我的需求进行的剪枝,具体怎么剪,还是要根据需求。

def cut_tree(tree):
    # find all leaves's node
    all_leaves = tree.leaves()
    # find all ids of leaves's node
    all_leaves_id = [ str(x).split(',')[1].split('=')[1] for x in all_leaves]
    for leaf_id in all_leaves_id:
        get_leaf_siblings = tree.siblings(leaf_id)
        siblings_id_list = []
        if get_leaf_siblings == []:
            all_leaves_id.remove(leaf_id)
        else:
            siblings_id_list.append(leaf_id)
            for get_leaf_sibling in get_leaf_siblings:
                siblings_id_list.append( str(get_leaf_sibling).split(',')[1].split('=')[1] )
            siblings_is_leaves = list(set(siblings_id_list) & set(all_leaves_id))
            if siblings_is_leaves == []:
                all_leaves_id.remove(leaf_id)
            else:
                # 叶子节点的父亲节点有兄弟,删除叶子
                get_leaf_parent = tree.parent(leaf_id)
                get_leaf_parent_id = str(get_leaf_parent).split(',')[1].split('=')[1]
                if tree.depth(leaf_id) > 3 and tree.siblings(get_leaf_parent_id) != []:
                    for siblings_id in siblings_is_leaves:
                        tree.remove_node( siblings_id) # 删除叶子节点
                        all_leaves_id.remove(siblings_id)
                else:
                    for siblings_id in siblings_is_leaves:
                        all_leaves_id.remove(siblings_id)
        return tree

你可能感兴趣的:(Python)