【问题标题】:how to get height of dependency tree with spacy?如何用spacy获得依赖树的高度?
【发布时间】:2020-10-31 01:58:13
【问题描述】:

我有一句话'今天我早点去上学' 我想使用 spacy 和迭代来获得依赖树的最大高度(深度)。

nlp = spacy.load("en_core_web_sm")
doc = nlp("today i go to school early")
height = 0
for token in doc:
   root = [token for token in doc if token.head == token][0]

我被困在这里,无法进一步导航。如果有任何问题,请您帮忙纠正我上面的代码?

【问题讨论】:

    标签: nlp spacy


    【解决方案1】:

    这里是基于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]
    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])
    

    【讨论】:

    • 谢谢,有没有办法返回深度的最大值?我尝试将 depths{} 放入函数中,但效果不佳
    猜你喜欢
    • 2016-08-05
    • 1970-01-01
    • 1970-01-01
    • 2018-08-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多