我问过一个问题,我怎样才能在NTLK树中正确导航。在
How do I properly navigate through an NLTK tree (or ParentedTree)? I would like to identify a certain leaf with the parent node "VBZ", then I would like to move from there further up the tree and to the left to identify the NP node.
并提供了以下插图:
我从汤米那里得到了以下(非常有帮助的)答案(谢谢!)公司名称:
from nltk.tree import *
np_trees = []
def traverse(t):
try:
t.label()
except AttributeError:
return
if t.label() == "VBZ":
current = t
while current.parent() is not None:
while current.left_sibling() is not None:
if current.left_sibling().label() == "NP":
np_trees.append(current.left_sibling())
current = current.left_sibling()
current = current.parent()
for child in t:
traverse(child)
tree = ParentedTree.fromstring("(S (NP (NNP)) (VP (VBZ) (NP (NNP))))")
traverse(tree)
print np_trees # [ParentedTree('NP', [ParentedTree('NNP', [])])]
但是我怎样才能包括我只提取那些具有NNP子节点的NP节点的条件呢?
如有任何帮助,我们将再次感谢。在
(一般来说,如果你们当中有什么关于NLTK树的专家,我很愿意和你聊聊天,并支付一些咖啡费,以换取一些见解。)
我通常将subtrees函数与过滤器结合使用。 稍微更改树以显示它现在只选择一个NP:
但是,当你的子树/x[0]没有标签时(例如,当它是终端时),这可能会崩溃。或者在NP完全为空时抛出索引器。但我认为这种情况不大可能发生。然而,很有可能我在监督这里的事情,你可能想建立一些额外的检查。。。在
相关问题 更多 >
编程相关推荐