how do i get the height of a dependency tree using spacy?

Here is a recursive implementation based on this question

import spacy

en_nlp = spacy.load('en_core_web_sm')
doc = en_nlp("The quick brown fox jumps over the lazy dog.")
depths = {}

def walk_tree(node, depth):
    depths[node.orth_] = depth
    if node.n_lefts + node.n_rights > 0:
        return [walk_tree(child, depth + 1) for child in node.children]

[walk_tree(sent.root, 0) for sent in doc.sents]

This prints:

{'jumps': 0, 'fox': 1, 'The': 2, 'quick': 2, 'brown': 2, 'over': 1, 'dog': 2, 'the': 3, 'lazy': 3, '.': 1}


If you just want the max depth and nothing else, this will do

def walk_tree(node, depth):
    if node.n_lefts + node.n_rights > 0:
        return max(walk_tree(child, depth + 1) for child in node.children)
        return depth

print([walk_tree(sent.root, 0) for sent in doc.sents])

CLICK HERE to find out more related problems solutions.

Leave a Comment

Your email address will not be published.

Scroll to Top