2016-11-20 9 views
0

私はnlpプロジェクトに取り組んでいます。依存関係ツリー内の位置に応じて単語をフィルタ処理したいと思います。例文についてnltkツリーから単語の深さを取得

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_ 

:私はこのpostからのコードを使用していますツリープロットに

「世界中の人々のグループが突然精神的にリンクされています」

私はこの木を持っています:

enter image description here

、私はチャイルズを持っていない言葉に興味がないんだけど、このケースでは

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

:私は手に入れたいものをこのツリーから

は、ツリー内の単語とそれに対応する深さを持つタプルのリストです:私はこれまでにできることは、子供がいる単語のリストだけを取得することです。このコードを使用しています。

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を使うと、ツリーの下のパスである "treepositions"を使って、あなたが望むことをすることができます。各パスは分岐選択のタプルです。 "人"の墓地は(0, 2, 1, 0)であり、あなたが見ることができるように、ノードの深さはその敷地の長さに過ぎません。

まず、私はそれらを除外することができますので、私は葉のパスを取得する:。なお、NLTKの木を

>>> 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 

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)) 

は、今では非終端ノードとその深さをリストアップするのは簡単です独自の表示方法があります。試してくださいprint(t)またはt.draw()、ポップアップウィンドウでツリーを描画します。

+0

私はspaCyから依存ツリーをプロットするためにnltkを使用しています。なぜなら、それは "children"メソッドを持っているからです。 http://stackoverflow.com/questions/36610179/how-to-get-the-dependency-tree-with-spacy –

関連する問題