Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
772 views
in Technique[技术] by (71.8m points)

python - NLTK tree data structure, finding a node, it's parent or children

I am using nltk's Tree data structure to work with parsetree strings.

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

The data structure, however, seems to be limited. Is it possible to get a node by it's string value and then navigate to top or bottom?

For example suppose you want to get the node with string value 'nice' and then see what's its parent, children, etc. Is it achievable via nltk's Tree?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

For NLTK 3.0, you want to use the ParentedTree subclass.

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

Using the sample tree you've given, create a ParentedTree and search for the node you want:

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]

You can iterate through the tree directly to get the child subtrees. The parent() method is used to find the parent tree for the given subtree.

Here's an example using a deeper tree for child and 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)

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...