How to get the dependency tree with spaCy?

后端 未结 7 2105
抹茶落季
抹茶落季 2020-12-04 09:31

I have been trying to find how to get the dependency tree with spaCy but I can\'t find anything on how to get the tree, only on how to navigate the tree.

7条回答
  •  执笔经年
    2020-12-04 10:05

    I also needed to do it so below full code:

    import sys
    def showTree(sent):
        def __showTree(token):
            sys.stdout.write("{")
            [__showTree(t) for t in token.lefts]
            sys.stdout.write("%s->%s(%s)" % (token,token.dep_,token.tag_))
            [__showTree(t) for t in token.rights]
            sys.stdout.write("}")
        return __showTree(sent.root)
    

    And if you want spacing for the terminal:

    def showTree(sent):
        def __showTree(token, level):
            tab = "\t" * level
            sys.stdout.write("\n%s{" % (tab))
            [__showTree(t, level+1) for t in token.lefts]
            sys.stdout.write("\n%s\t%s [%s] (%s)" % (tab,token,token.dep_,token.tag_))
            [__showTree(t, level+1) for t in token.rights]
            sys.stdout.write("\n%s}" % (tab))
        return __showTree(sent.root, 1)
    

提交回复
热议问题