2014-09-12 45 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

相關問題