2011-10-01 10 views
11

Sto utilizzando NLTK RegexpParser per estrarre i gruppi non vuoti e i gruppi di verbi dai token con tag.NLTK Chunking e cammino dell'albero dei risultati

Come si cammina l'albero risultante per trovare solo i blocchi che sono gruppi NP o V?

from nltk.chunk import RegexpParser 

grammar = ''' 
NP: {<DT>?<JJ>*<NN>*} 
V: {<V.*>}''' 
chunker = RegexpParser(grammar) 
token = [] ## Some tokens from my POS tagger 
chunked = chunker.parse(tokens) 
print chunked 

#How do I walk the tree? 
#for chunk in chunked: 
# if chunk.??? == 'NP': 
#   print chunk 

(S (NP Carrier/NN) per/IN tessuto-/JJ e/CC coltura cellulare/JJ per/IN (NP l'/ DT preparato/NN) di/iN (NP protesi/NNS) e/CC (NP impianto/NN) (V contenente/VBG) (NP l'/ DT portante/NN) ./.)

risposta

11

Questo dovrebbe funzionare :

for n in chunked: 
    if isinstance(n, nltk.tree.Tree):    
     if n.label() == 'NP': 
      do_something_with_subtree(n) 
     else: 
      do_something_with_leaf(n) 
+0

Mi dà AttributeError: 'tupla' oggetto non ha attributo 'nodo' n è di

+0

risposta a cura ... –

+1

funziona come un fascino - grazie! –

0

piccolo errore token

from nltk.chunk import RegexpParser 
grammar = ''' 
NP: {<DT>?<JJ>*<NN>*} 
V: {<V.*>}''' 
chunker = RegexpParser(grammar) 
token = [] ## Some tokens from my POS tagger 
//chunked = chunker.parse(tokens) // token defined in the previous line but used tokens in chunker.parse(tokens) 
chunked = chunker.parse(token) // Change in this line 
print chunked 
0

risposta di Savino è grande, ma è anche interessante notare che sottostrutture sono reperibili indice pure, ad esempio

for n in range(len(chunked)): 
    do_something_with_subtree(chunked[n]) 
Problemi correlati