How to Traverse an NLTK Tree object?

元气小坏坏 提交于 2019-11-26 10:02:43

问题


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?


回答1:


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.



来源:https://stackoverflow.com/questions/31689621/how-to-traverse-an-nltk-tree-object

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!