2013-02-12 7 views
19

私が使用して文をチャンクしました:nltk.tree.Treeをナビゲートするには?

grammar = '''                            
    NP:                              
     {<DT>*(<NN.*>|<JJ.*>)*<NN.*>}                      
    NVN:                             
     {<NP><VB.*><NP>}                          
    ''' 
chunker = nltk.chunk.RegexpParser(grammar) 
tree = chunker.parse(tagged) 
print tree 

結果は以下のようになります。

(S 
    (NVN 
    (NP The_Pigs/NNS) 
    are/VBP 
    (NP a/DT Bristol-based/JJ punk/NN rock/NN band/NN)) 
    that/WDT 
    formed/VBN 
    in/IN 
    1977/CD 
    ./.) 

しかし、今、私はそれをナビゲートする方法を理解しようとして立ち往生しています。私はNVNサブツリーを見つけて、左側の名詞句( "The_Pigs")、動詞( "are")、右側の名詞句( "Bristolベースのパンク・ロック・バンド")にアクセスしたい。それ、どうやったら出来るの?

+0

と、これらのメソッドplaywithが

http://www.nltk.org/_modules/nltk/tree.html #ALL APIは、あなたがして、私はあなたに明確なを与えることができ、リーフノードとの完全な文法を投稿することができ例? – alvas

答えて

4

これを試してください:

[( 'The_Pigs'、 'NNS')]

( 'である'、 'VBP')

for a in tree: 
     if type(a) is nltk.Tree: 
      if a.node == 'NVN': # This climbs into your NVN tree 
       for b in a: 
        if type(b) is nltk.Tree and b.node == 'NP': 
         print b.leaves() # This outputs your "NP" 
        else: 
         print b # This outputs your "VB.*" 

それは、これを出力しますブリック・ベース、JJ、パンク、NN、ロック、NN、バンド、NN、 ')]

8

もちろん、あなた自身のd epth first search ...しかし、より簡単な(より良い)方法があります。すべてのサブツリーがNVMをルートにするようにするには、filterパラメータを定義したTreeのsubtreeメソッドを使用します。

>>> print t 
(S 
    (NVN 
     (NP The_Pigs/NNS) 
     are/VBP 
     (NP a/DT Bristol-based/JJ punk/NN rock/NN band/NN)) 
    that/WDT 
    formed/VBN 
    in/IN 
    1977/CD 
    ./.) 
>>> for i in t.subtrees(filter=lambda x: x.node == 'NVN'): 
...  print i 
... 
(NVN 
    (NP The_Pigs/NNS) 
    are/VBP 
    (NP a/DT Bristol-based/JJ punk/NN rock/NN band/NN)) 
+2

をPython 3.5とNLTK 3.2.2で使用する場合、ラムダ関数はnodeのlabel()プロパティを使用する必要があります:filter = lambda x:x.label()== "NP" – Maciej

14

試してみてください。ここ

ROOT = 'ROOT' 
tree = ... 
def getNodes(parent): 
    for node in parent: 
     if type(node) is nltk.Tree: 
      if node.label() == ROOT: 
       print "======== Sentence =========" 
       print "Sentence:", " ".join(node.leaves()) 
      else: 
       print "Label:", node.label() 
       print "Leaves:", node.leaves() 

      getNodes(node) 
     else: 
      print "Word:", node 

getNodes(tree) 
+0

別のDFSの例( 'ParentedTree'):http ://stackoverflow.com/a/25972853/4115369 –

+0

よろしくお願いいたします。 NLTKのインタフェースが時間外に変更される可能性があることに注意してください。 – danger89

3

は、ラベル「NP」

def filt(x): 
    return x.label()=='NP' 

for subtree in t.subtrees(filter = filt): # Generate all subtrees 
    print subtree 

兄弟のために、あなたが方法を見てみたいかもしれないとのすべてのサブツリーを生成するためのコードサンプルですParentedTree.left_siblings()

詳細については、次のリンクを参考にしてください。

http://www.nltk.org/howto/tree.html #some基本的な使い方と例 http://nbviewer.ipython.org/github/gmonce/nltk_parsing/blob/master/1.%20NLTK%20Syntax%20Trees.ipynb #Aノートソース

関連する問題