【问题标题】:Get the depth of words from a nltk tree从 nltk 树中获取单词的深度
【发布时间】:2016-11-22 09:21:35
【问题描述】:

我正在做一个 nlp 项目,我想根据它在依赖关系树中的位置过滤掉单词。

为了绘制树,我使用了来自 post 的代码:

def to_nltk_tree(node):

    if node.n_lefts + node.n_rights > 0:
        return Tree(node.orth_, [to_nltk_tree(child) for child in node.children])
    else:
        return node.orth_

对于一个例句:

“世界各地的一群人突然在精神上联系在一起”

我得到了这棵树:

我想从这棵树中得到一个元组列表,其中包含单词及其在树中的相应深度:

[(linked,1),(are,2),(suddenly,2),(mentally,2),(group,2),(A,3),(of,3),(people,4)....]

对于这种情况,我对没有孩子的单词不感兴趣:[are,suddenly,mentally,A,the] 所以到目前为止我所能做的就是只获取有孩子的单词列表,所以我使用这个代码:

def get_words(root,words):
    children = list(root.children)
    for child in children:
        if list(child.children):
            words.append(child)
            get_words(child,words)
    return list(set(words)

[to_nltk_tree(sent.root).pretty_print() for sent in doc.sents]
s_root = list(doc.sents)[0].root
words = []
words.append(s_root)    
words = get_words(s_root,words)
words

[around, linked, world, of, people, group]

从这里我怎样才能得到所需的带有单词及其各自深度的元组?

【问题讨论】:

    标签: python tree nlp nltk spacy


    【解决方案1】:

    你确定你的代码中有一个 nltk Tree 吗? nltk 的Tree 类没有children 属性。使用 nltk Tree,您可以使用“treepositions”(即树下的路径)来做您想做的事情。每条路径都是一个分支选择元组。 “人”的树位置是(0, 2, 1, 0),你可以看到一个节点的深度就是它的树位置的长度。

    首先我得到叶子的路径,以便排除它们:

    t = nltk.Tree.fromstring("""(linked (are suddenly mentally 
                                         (group A (of (people (around (world the)))))))""")
    n_leaves = len(t.leaves())
    leavepos = set(t.leaf_treeposition(n) for n in range(n_leaves))
    

    现在很容易列出非终端节点及其深度:

    >>> for pos in t.treepositions():
            if pos not in leavepos:
                print(t[pos].label(), len(pos))
    linked 0
    are 1
    group 2
    of 3
    people 4
    around 5
    world 6
    

    顺便说一下,nltk 树有自己的显示方法。试试print(t)t.draw(),在弹出窗口中绘制树。

    【讨论】:

    • 我正在使用 nltk 从 spaCy 绘制依赖关系树,这就是它具有“children”方法的原因。 stackoverflow.com/questions/36610179/…
    • 为什么这不适用于所有节点? for pos in t.treepositions(): print(t[pos].label(), len(pos))获取AttributeError: 'str' object has no attribute 'label'
    • 因为nltk.Tree 叶节点是字符串。只有非终结符才有标签属性。试试 my 代码,它可以工作。
    猜你喜欢
    • 1970-01-01
    • 2016-11-22
    • 2016-07-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-06-19
    • 2013-10-16
    • 1970-01-01
    相关资源
    最近更新 更多