【发布时间】:2016-03-17 13:29:57
【问题描述】:
我正在尝试遍历一棵树,并将某些子树放入特定的数据结构中。我认为一个例子是最好的解释方式:
对于这棵树,我想要根节点及其子节点。然后任何有自己的孩子的孩子都应该以同样的方式遍历,依此类推。所以对于上面的树,我们最终会得到一个数据结构,例如:
[
(a, [b, c]),
(c, [d, e, f]),
(f, [g, h]),
]
到目前为止,我有一些代码可以生成这个,但是有一个问题是它停止得太早了(或者看起来就是这样):
from spacy.en import English
def _subtrees(sent, root=None, subtrees=[]):
if not root:
root = sent.root
children = list(root.children)
if not children:
return subtrees
subtrees.append((root, [child for child in children]))
for child in children:
return _subtrees(sent, child, subtrees)
nlp = English()
doc = nlp('they showed us an example')
print(_subtrees(list(doc.sents)[0]))
请注意,此代码不会生成与图像中相同的树。我觉得生成器也更适合这里,但我的 generator-fu 甚至比我的 recursion-fu 还要糟糕。
【问题讨论】:
-
你看到this question了吗?
-
不,但是现在看一下,虽然我看到了很多一般的树遍历,但没有任何启发我能够解决我的问题。
-
您能否在问题的末尾提供一个完整的可运行示例,甚至可以提供示例输入,以便我们可以将其复制并粘贴到编辑器中并尝试处理它?
-
我将代码编辑为可运行,需要 spacy(来自 pypi)。
-
从代码中看不出树形数据结构。可以打印出
repr(list(doc.sents)[0]),并显示结果吗?