2012-02-05 24 views
5

Sto cercando di trovare le collocazioni con NLTK in un testo utilizzando il metodo incorporato.Python nltk: Trova collocazioni senza parole separate da punti

Ora sto avendo il seguente esempio di testo (prova e foo si susseguono, ma c'è un confine frase in mezzo):

content_part = """test. foo 0 test. foo 1 test. 
       foo 2 test. foo 3 test. foo 4 test. foo 5""" 

Risultato da tokenizzazione e collocations() è la seguente:

print nltk.word_tokenize(content_part) 
# ['test.', 'foo', 'my', 'test.', 'foo', '1', 'test.', 
# 'foo', '2', 'test.', 'foo', '3', 'test.', 'foo', '4', 'test.', 'foo', '5'] 

print nltk.Text(nltk.word_tokenize(content_part)).collocations() 
# test. foo 

Come può Impedisco NLTK da:

  1. Compreso il punto nella mia tokenizzazione
  2. non trovano collocazioni() oltre i confini di frase?

Quindi in questo esempio non dovrebbe stampare alcuna collocazione, ma immagino che si possano immaginare testi più complicati in cui ci sono anche collocazioni all'interno di frasi.

Posso immaginare che ho bisogno di usare il Punkt frase segmenter, ma poi non so come metterli di nuovo insieme per trovare collocazioni con NLTK (collocation() sembra essere più potente di roba solo contando me stesso).

risposta

8

È possibile utilizzare WordPunctTokenizer per separare la punteggiatura dalle parole e successivamente filtrare i bigram con la punteggiatura con apply_word_filter().

La stessa cosa può essere utilizzata per i trigrammi per non trovare le collocazioni sui bordi della frase.

from nltk import bigrams 
from nltk import collocations 
from nltk import FreqDist 
from nltk.collocations import * 
from nltk import WordPunctTokenizer 

content_part = """test. foo 0 test. foo 1 test. 
       foo 2 test. foo 3 test. foo 4 test, foo 4 test.""" 

tokens = WordPunctTokenizer().tokenize(content_part) 

bigram_measures = collocations.BigramAssocMeasures() 
word_fd = FreqDist(tokens) 
bigram_fd = FreqDist(bigrams(tokens)) 
finder = BigramCollocationFinder(word_fd, bigram_fd) 

finder.apply_word_filter(lambda w: w in ('.', ',')) 

scored = finder.score_ngrams(bigram_measures.raw_freq) 

print tokens 
print sorted(finder.nbest(bigram_measures.raw_freq,2),reverse=True) 

uscita:

['test', '.', 'foo', '0', 'test', '.', 'foo', '1', 'test', '.', 'foo', '2', 'test', '.', 'foo', '3', 'test', '.', 'foo', '4', 'test', ',', 'foo', '4', 'test', '.'] 
[('4', 'test'), ('foo', '4')] 
Problemi correlati