2011-10-01 25 views
11

Estoy usando NLTK RegexpParser para extraer noungroups y verbgroups de tokens etiquetados.NLTK Chunking y caminar en el árbol de resultados

¿Cómo ando el árbol resultante para encontrar solo los fragmentos que son grupos 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) para/IN tejido-/JJ y/CC de cultivo celular/JJ para/IN (NP el/preparación DT/NN) de/IN (implantes NP/NNS) y/CC (implante NP/NN) (V que contiene/VBG) (NP el portador/DT/NN) ./.)

Respuesta

11

Esto debería funcionar :

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

Me da AttributeError: 'tupla' objeto no tiene atributo 'nodo' n es de

+0

respuesta editado ... –

+1

funciona como un encanto - gracias! –

0

pequeño error en 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

respuesta de Savino es grande, pero es también digno de mención que los subárboles se puede acceder por el índice, así, por ejemplo,

for n in range(len(chunked)): 
    do_something_with_subtree(chunked[n]) 
Cuestiones relacionadas