使用anytree从带有缩进的文件生成树

9bfwbjaz  于 2021-08-20  发布在  Java
关注(0)|答案(1)|浏览(413)

我用anytree从文件生成一棵树, Tree.txt . 每个缩进是3个空格(

). 以下是我的文件的外观:

ROOT
   Node1
      Node2
         Node3
            Node4
   Node5
   Node6

以下是我到目前为止对生成代码的了解:

from anytree import Node, RenderTree, find_by_attr

def parse_tree():
    with open('Tree.txt', 'r') as file:
        file_contents = file.readlines()
        root = Node("ROOT")

        current_indent = -1 # store index for comparing later
        for (index, line) in enumerate(file_contents):

            leading_spaces = len(line) - len(line.lstrip(' '))
            indent = int(leading_spaces / 3) # indent = 3 spaces

            if indent > current_indent: # node must be 1 level down

                # get the previous Node (1 level up)
                previous_line = file_contents[index - 1].strip()
                current_line = line.strip()
                parent = find_by_attr(root, previous_line)
                Node(current_line, parent=parent) # start searching from top node (root) for `previous_line`
                current_indent = indent
            else: # node is on same level or higher
                print(f"What to do for {line.strip()}?") 
                # what should I do here?

        print(RenderTree(root)) # print the output

parse_tree()

但是,这会打印出:

What to do for Node5?
What to do for Node6?
Node('/ROOT')
└── Node('/ROOT/Node1')
    └── Node('/ROOT/Node1/Node2')
        └── Node('/ROOT/Node1/Node2/Node3')
            └── Node('/ROOT/Node1/Node2/Node3/Node4')

生成的树很好,但直到 Node4 - Node5Node6 他们失踪了。这是意料之中的,因为我没有处理当前缩进小于前一缩进的情况(请参见 # what should I do here? ).
当当前缩进小于上一缩进时,我应该怎么做?我知道我需要上去 n 级别更高,但我如何确定这是哪个级别?

67up9zun

67up9zun1#

需要一种堆栈来跟踪节点的深度,然后可以使用初始空间的数量来确定将每个叶附加到哪个父节点。e、 例如,三个空格意味着向下一级,因此需要附加到堆栈中索引0处的根节点(你也可以说,通过使用堆栈,我们得到了树叶的绝对深度,而你试图相对地解决它(如果我有任何意义的话)。我怀疑如果你使用 find_by_attr ,如果有同名的叶子,这可能不起作用。

treestring = '''
ROOT
   Node1
      Node2
         Node3
            Node4
   Node5
   Node6'''.strip()

leaves = treestring.splitlines()

# initialize stack with the root node

stack = {0: Node(leaves.pop(0))}

for leaf in leaves:

    # determine the node's depth
    leading_spaces = len(leaf)-len(leaf.lstrip(' '))
    level = int(leading_spaces/3)

    # add the node to the stack, set as parent the node that's one level up
    stack[level] = Node(leaf.strip(), parent=stack[level-1])

tree = stack[0]

for pre, _, node in RenderTree(tree):
    print(f"{pre}{node.name}")

结果:

ROOT
├── Node1
│   └── Node2
│       └── Node3
│           └── Node4
├── Node5
└── Node6

相关问题