2014-09-12 234 views
5

我正在使用nltk的树数据结构来处理分析树的字符串。NLTK树数据结构,找到一个节点,它是父母或子女

from nltk.tree import Tree 
parsed = Tree('(ROOT (S (NP (PRP It)) (VP (VBZ is) (ADJP (RB so) (JJ nice))) (. .)))') 

但是,数据结构似乎是有限的。 是否有可能通过它的字符串值获取节点,然后导航到顶部或底部?

例如,假设您想要获取字符串值为'nice'的节点,然后查看它的父项,子项等是否可以通过nltk的Tree实现?

+0

此外,见http://stackoverflow.com/questions/16407880/extracting-specific-leaf-value-from-nltk-tree -structure-with-python?rq = 1 – Jesuisme 2014-09-22 14:45:39

回答

10

对于NLTK 3.0,您希望使用ParentedTree子类。

http://www.nltk.org/api/nltk.html#nltk.tree.ParentedTree

使用您给出的样本树,营造ParentedTree并搜索你想要的节点:

from nltk.tree import ParentedTree 
ptree = ParentedTree.fromstring('(ROOT (S (NP (PRP It)) \ 
     (VP (VBZ is) (ADJP (RB so) (JJ nice))) (. .)))') 

leaf_values = ptree.leaves() 

if 'nice' in leaf_values: 
    leaf_index = leaf_values.index('nice') 
    tree_location = ptree.leaf_treeposition(leaf_index) 
    print tree_location 
    print ptree[tree_location] 

您可以通过树遍历直接让孩子子树。 parent()方法用于查找给定子树的父树。

下面是使用的儿童及家长更深入的树的例子:

from nltk.tree import ParentedTree 
ptree = ParentedTree.fromstring('(ROOT (S (NP (JJ Congressional) \ 
    (NNS representatives)) (VP (VBP are) (VP (VBN motivated) \ 
    (PP (IN by) (NP (NP (ADJ shiny) (NNS money))))))) (. .))') 

def traverse(t): 
    try: 
     t.label() 
    except AttributeError: 
     return 
    else: 

     if t.height() == 2: #child nodes 
      print t.parent() 
      return 

     for child in t: 
      traverse(child) 

traverse(ptree) 
+0

另外:“树位置”是一个元组,描述树下的路径。所以如果你有一个节点的路径,例如在答案中的'tree_location',它的父节点将在'tree_location [: - 1]'处。这适用于'Tree'和'ParentedTree'。 – alexis 2015-12-02 20:09:32