2016-11-20 65 views
0

我正在处理一个nlp项目,我想根据它在依赖关系树中的位置来筛选出单词。从nltk树中获取词的深度

要绘制我正在使用的代码从这个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_ 

对于一个例句:

“A组的世界各地的人们突然精神上联系”

我得到这棵树:

enter image description here

从这个树就是我想要得到的是树中的单词和相应的深度元组的列表:

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

对于这种情况,我在没有孩子的话不感兴趣: [是,突然,精神上,A,] 因此,我迄今能够做到的只是获得有儿童的单词列表,因此我使用此代码:

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] 

从这我怎么能得到所需的元组与单词和其各自的深度?

回答

1

你确定这是你的代码中的nltk Tree? nltk的Tree类没有children属性。使用nltk Tree,你可以通过使用树结构中的“树结构”来完成你想要的任务。每条路径都是分支选择的元组。 “people”的树形结构为(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(),它在弹出窗口中绘制树。

+0

我正在使用nltk从spaCy绘制依赖关系树,这就是为什么它有“子”方法。 http://stackoverflow.com/questions/36610179/how-to-get-the-dependency-tree-with-spacy –