parsing tree nlp nltk depth-first-search

parsing - ¿Cómo atravesar un objeto de árbol NLTK?



tree nlp (1)

Dado un análisis entre corchetes, podría convertirlo en un objeto Tree en NLTK como tal:

>>> 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(''.'', [''.''])])])

Pero cuando trato de atravesarlo, solo puedo acceder al árbol más superior:

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

Podría ir un nivel más profundo de la siguiente manera:

>>> 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) (. .)

Pero, ¿hay alguna manera de atravesar todos los subárboles en profundidad?

¿Cómo se debe atravesar un árbol en NLTK?

¿Cómo atravesar todos los subárboles en NLTK?


Tal vez estoy pasando por alto las cosas, pero ¿es esto lo que buscas?

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)

Atraviesa tu árbol en profundidad primero.