Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to Traverse an NLTK Tree object?

Given a bracketed parse, I could convert it into a Tree object in NLTK as such:

>>> from nltk.tree import Tree
>>> s = '(ROOT (S (NP (NNP Europe)) (VP (VBZ is) (PP (IN in) (NP (DT the) (JJ same) (NNS trends)))) (. .)))'
>>> Tree.fromstring(s)
Tree('ROOT', [Tree('S', [Tree('NP', [Tree('NNP', ['Europe'])]), Tree('VP', [Tree('VBZ', ['is']), Tree('PP', [Tree('IN', ['in']), Tree('NP', [Tree('DT', ['the']), Tree('JJ', ['same']), Tree('NNS', ['trends'])])])]), Tree('.', ['.'])])])

But when I try to traverse it, I can only access the top most Tree:

>>> for i in Tree.fromstring(s):
...     print i
... 
(S
  (NP (NNP Europe))
  (VP (VBZ is) (PP (IN in) (NP (DT the) (JJ same) (NNS trends))))
  (. .))
>>> for i in Tree.fromstring(s):
...     print i, i.label()
... 
(S
  (NP (NNP Europe))
  (VP (VBZ is) (PP (IN in) (NP (DT the) (JJ same) (NNS trends))))
  (. .)) S
>>> 

I could go one level deep as follows:

>>> for i in Tree.fromstring(s):
...     print i.subtrees()
... 
<generator object subtrees at 0x7f1eb1571410>
>>> for i in Tree.fromstring(s):
...     for j in i.subtrees():
...             print j
... 
(S
  (NP (NNP Europe))
  (VP (VBZ is) (PP (IN in) (NP (DT the) (JJ same) (NNS trends))))
  (. .))
(NP (NNP Europe))
(NNP Europe)
(VP (VBZ is) (PP (IN in) (NP (DT the) (JJ same) (NNS trends))))
(VBZ is)
(PP (IN in) (NP (DT the) (JJ same) (NNS trends)))
(IN in)
(NP (DT the) (JJ same) (NNS trends))
(DT the)
(JJ same)
(NNS trends)
(. .)

But is there a way to traverse all subtrees depth wise?

How should one traverse a tree in NLTK?

How to traverse all subtrees in NLTK?

like image 458
alvas Avatar asked Jul 29 '15 01:07

alvas


1 Answers

Maybe I'm overlooking things, but is this what you're after?

import nltk
s = '(ROOT (S (NP (NNP Europe)) (VP (VBZ is) (PP (IN in) (NP (DT the) (JJ same) (NNS trends)))) (. .)))'
tree = nltk.tree.Tree.fromstring(s)
def traverse_tree(tree):
    # print("tree:", tree)
    for subtree in tree:
        if type(subtree) == nltk.tree.Tree:
            traverse_tree(subtree)
traverse_tree(tree)

It traverses your tree depth-first.

like image 50
Igor Avatar answered Sep 22 '22 22:09

Igor