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 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…