How to Traverse an NLTK Tree object?

后端 未结 1 729
闹比i
闹比i 2020-11-29 12:54

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          


        
相关标签:
1条回答
  • 2020-11-29 13:18

    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.

    0 讨论(0)
提交回复
热议问题