这是基于此问题的递归实现
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]
print(depths)
print(max(depths.values()))
打印:
{'jumps': 0, 'fox': 1, 'The': 2, 'quick': 2, 'brown': 2, 'over': 1, 'dog': 2, 'the': 3, 'lazy': 3, '.': 1}
3
编辑:
如果您只想要最大深度而已,则可以
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)
else:
return depth
print([walk_tree(sent.root, 0) for sent in doc.sents])
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句