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
1.5k views
in Technique[技术] by (71.8m points)

parsing - 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?

See Question&Answers more detail:os

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

1 Reply

0 votes
by (71.8m points)

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.


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

...