あなたはツリーを走査して確認することができます
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))
チェックします。http:// WWW。 nltk.org/_modules /nltk/util.html#breadth_first – RAVI