2016-09-05 6 views
0
(ROOT 
    (S 
    (NP (NNP Barack) (NNP Obama)) 
    (VP 
     (VBZ is) 
     (NP 
     (NP (DT the) (JJ 44th) (CC and) (JJ current) (NN president)) 
     (PP (IN of) (NP (DT the) (NNP USA))))) 
    (. .))) 

このサブツリーの値を取得する方法は、トップNPツリーですか?最初のNP値を得るためにBFSを使ってツリーをトラバースする方法は? NLTK

(NP (NNP Barack) (NNP Obama)) 
+0

チェックします。http:// WWW。 nltk.org/_modules /nltk/util.html#breadth_first – RAVI

答えて

0

あなたはツリーを走査して確認することができます

isinstance(child, Tree)場合とchild.label()=="NP"コード:

from nltk import Tree 
from nltk.util import breadth_first 

parse_str = "(ROOT (S (NP (NNP Barack) (NNP Obama)) (VP (VBZ is) (NP (NP (DT the) (JJ 44th) (CC and) (JJ current) (NN president)) (PP (IN of) (NP (DT the) (NNP USA))))) (. .)))" 
t = Tree.fromstring(parse_str) 

#alltrees = [] 

def getsubtrees(t): 
    subtrees = [] 
    for subt in t: 
     for child in subt: 
      if isinstance(child, Tree) and child.label()=="NP": 
       print child 
       break # Remove break to print all NPs 

      if isinstance(child, Tree): 
       subtrees.append(child) 

    #alltrees.append(subtrees) 
    if(len(subtrees)>1): 
     getsubtrees(subtrees) 

getsubtrees(t) 
#print alltrees 

出力:

(NP (NNP Barack) (NNP Obama)) 
+0

ありがとうございます。あなたは私をたくさん助けます – bob90937

関連する問題