2015-08-05 13 views
8

ho usato di NLTK ne_chunk per estrarre entità con nome da un testo:NLTK Chiamato Il riconoscimento delle entità a una lista Python

my_sent = "WASHINGTON -- In the wake of a string of abuses by New York police officers in the 1990s, Loretta E. Lynch, the top federal prosecutor in Brooklyn, spoke forcefully about the pain of a broken trust that African-Americans felt and said the responsibility for repairing generations of miscommunication and mistrust fell to law enforcement." 


nltk.ne_chunk(my_sent, binary=True) 

Ma io non riesco a capire come salvare queste entità a un elenco? Per esempio. -

print Entity_list 
('WASHINGTON', 'New York', 'Loretta', 'Brooklyn', 'African') 

Grazie.

+0

Cosa significa 'ne_chunk()' tornare invece? A cosa esattamente sei bloccato? – lenz

+0

possibile duplicato di [Nome entità di riconoscimento con espressione regolare: NLTK] (http://stackoverflow.com/questions/24398536/named-entity-recognition-with-regular-expression-nltk) – alvas

+0

Quando eseguo il codice ottengo un IndexError – MERose

risposta

18

nltk.ne_chunk restituisce un oggetto nltk.tree.Tree nidificato in modo che avrebbe dovuto attraversare l'oggetto Tree per raggiungere il NES.

Date un'occhiata a Named Entity Recognition with Regular Expression: NLTK

>>> from nltk import ne_chunk, pos_tag, word_tokenize 
>>> from nltk.tree import Tree 
>>> 
>>> def get_continuous_chunks(text): 
...  chunked = ne_chunk(pos_tag(word_tokenize(text))) 
...  prev = None 
...  continuous_chunk = [] 
...  current_chunk = [] 
...  for i in chunked: 
...    if type(i) == Tree: 
...      current_chunk.append(" ".join([token for token, pos in i.leaves()])) 
...    elif current_chunk: 
...      named_entity = " ".join(current_chunk) 
...      if named_entity not in continuous_chunk: 
...        continuous_chunk.append(named_entity) 
...        current_chunk = [] 
...    else: 
...      continue 
...  return continuous_chunk 
... 
>>> my_sent = "WASHINGTON -- In the wake of a string of abuses by New York police officers in the 1990s, Loretta E. Lynch, the top federal prosecutor in Brooklyn, spoke forcefully about the pain of a broken trust that African-Americans felt and said the responsibility for repairing generations of miscommunication and mistrust fell to law enforcement." 
>>> get_continuous_chunks(my_sent) 
['WASHINGTON', 'New York', 'Loretta E. Lynch', 'Brooklyn'] 
4

Come si ottiene un tree come valore di ritorno, penso che si desidera scegliere quelle sottostrutture che sono etichettati con NE

Ecco un semplice esempio per raccogliere tutti coloro che in un elenco:

import nltk 

my_sent = "WASHINGTON -- In the wake of a string of abuses by New York police officers in the 1990s, Loretta E. Lynch, the top federal prosecutor in Brooklyn, spoke forcefully about the pain of a broken trust that African-Americans felt and said the responsibility for repairing generations of miscommunication and mistrust fell to law enforcement." 

parse_tree = nltk.ne_chunk(nltk.tag.pos_tag(my_sent.split()), binary=True) # POS tagging before chunking! 

named_entities = [] 

for t in parse_tree.subtrees(): 
    if t.label() == 'NE': 
     named_entities.append(t) 
     # named_entities.append(list(t)) # if you want to save a list of tagged words instead of a tree 

print named_entities 

Questo dà:

[Tree('NE', [('WASHINGTON', 'NNP')]), Tree('NE', [('New', 'NNP'), ('York', 'NNP')])] 

o come una lista di liste:

[[('WASHINGTON', 'NNP')], [('New', 'NNP'), ('York', 'NNP')]] 

Vedi anche: How to navigate a nltk.tree.Tree?

2

Un Tree è una lista. I blocchi sono sottostrutture, le parole non troncate sono stringhe regolari. Quindi andiamo giù nella lista, estraiamo le parole da ciascun blocco e ci uniamo a loro.

>>> chunked = nltk.ne_chunk(my_sent) 
>>> 
>>> [ " ".join(w for w, t in elt) for elt in chunked if isinstance(elt, nltk.Tree) ] 
['WASHINGTON', 'New York', 'Loretta E. Lynch', 'Brooklyn'] 
2

È inoltre possibile estrarre la label di ogni nome dell'entità nel testo utilizzando questo codice:

import nltk 
for sent in nltk.sent_tokenize(sentence): 
    for chunk in nltk.ne_chunk(nltk.pos_tag(nltk.word_tokenize(sent))): 
     if hasattr(chunk, 'label'): 
     print(chunk.label(), ' '.join(c[0] for c in chunk)) 

uscita:

GPE WASHINGTON 
GPE New York 
PERSON Loretta E. Lynch 
GPE Brooklyn 

Si può vedere Washington, New York e Brooklyn sono GPE significa entità geopolitiche

e Loretta E. Lynch è un PERSON

0

uso tree2conlltags da nltk.chunk. Anche ne_chunk ha bisogno di tagging pos che taggano token di parole (quindi ha bisogno di word_tokenize).

from nltk import word_tokenize, pos_tag, ne_chunk 
from nltk.chunk import tree2conlltags 

sentence = "Mark and John are working at Google." 
print(tree2conlltags(ne_chunk(pos_tag(word_tokenize(sentence)) 
"""[('Mark', 'NNP', 'B-PERSON'), 
    ('and', 'CC', 'O'), ('John', 'NNP', 'B-PERSON'), 
    ('are', 'VBP', 'O'), ('working', 'VBG', 'O'), 
    ('at', 'IN', 'O'), ('Google', 'NNP', 'B-ORGANIZATION'), 
    ('.', '.', 'O')] """ 

Questo vi darà una lista di tuple: [(token pos_tag, name_entity_tag)] Se questo elenco non è esattamente ciò che si vuole, è certamente più facile per analizzare l'elenco che si desidera uscire da questa lista quindi un albero nltk.

Codice e dettagli da this link; check it out per ulteriori informazioni

Modifica Aggiunto uscita docstring

Problemi correlati