从文件中读取数据并使用python中的anytree创建树 [英] Read data from a file and create a tree using anytree in python
问题描述
有没有办法从文件中读取数据并使用anytree构造树?
Is there a way to read data from a file and construct a tree using anytree?
Parent Child
A A1
A A2
A2 A21
我可以使用静态值来做到这一点,如下所示.但是,我想通过从具有anytree的文件中读取数据来实现此自动化.
I can do it with static values as follows. However, I want to automate this by reading the data from a file with anytree.
>>> from anytree import Node, RenderTree
>>> A = Node("A")
>>> A1 = Node("A1", parent=A)
>>> A2 = Node("A2", parent=A)
>>> A21 = Node("A21", parent=A2)
输出为
A
├── A1
└── A2
└── A21
推荐答案
这假定条目的顺序是始终始终将父节点作为另一个节点的子节点引入(不包括根节点).
This assumes that the entries are in such an order that a parent node was always introduced as a child of another node beforehand (root excluded).
牢记这一点,然后我们可以遍历各行,拆分它们(我使用了split
,正则表达式也可以使用)并创建新节点.
With that in mind, we can then iterate over the lines, split them (I used split
, regex would work too) and create the new nodes.
关于如何通过名称获得对父代的引用,我提出了两种解决方案:
For how to get a reference to the parent by name, I came up with two solutions:
首先,使用任意树find_by_attr
from anytree import Node, RenderTree, find_by_attr
with open('input.txt', 'r') as f:
lines = f.readlines()[1:]
root = Node(lines[0].split(" ")[0])
for line in lines:
line = line.split(" ")
Node("".join(line[1:]).strip(), parent=find_by_attr(root, line[0]))
for pre, _, node in RenderTree(root):
print("%s%s" % (pre, node.name))
第二,只需在创建它们时将它们缓存在字典中即可.
Second, just cache them in a dict while we create them:
from anytree import Node, RenderTree, find_by_attr
with open('input.txt', 'r') as f:
lines = f.readlines()[1:]
root = Node(lines[0].split(" ")[0])
nodes = {}
nodes[root.name] = root
for line in lines:
line = line.split(" ")
name = "".join(line[1:]).strip()
nodes[name] = Node(name, parent=nodes[line[0]])
for pre, _, node in RenderTree(root):
print("%s%s" % (pre, node.name))
input.txt
Parent Child
A A1
A A2
A2 A21
输出:
A
├── A1
└── A2
└── A21
这篇关于从文件中读取数据并使用python中的anytree创建树的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!