2013-01-16 10 views
15

Ho il seguente codice. So che posso usare la funzione apply_freq_filter per filtrare le collocazioni che sono inferiori al conteggio di frequenza. Tuttavia, non so come ottenere le frequenze di tutte le tuple di n-grammi (nel mio caso bi-gram) in un documento, prima di decidere quale frequenza impostare per il filtraggio. Come puoi vedere sto usando la classe nltk collocations.conteggio della frequenza n-gram in python nltk

import nltk 
from nltk.collocations import * 
line = "" 
open_file = open('a_text_file','r') 
for val in open_file: 
    line += val 
tokens = line.split() 

bigram_measures = nltk.collocations.BigramAssocMeasures() 
finder = BigramCollocationFinder.from_words(tokens) 
finder.apply_freq_filter(3) 
print finder.nbest(bigram_measures.pmi, 100) 
+3

Hai provato 'finder.ngram_fd.viewitems()'? –

+0

Grazie finder.ngram_fd.viewitems() funziona! – Rkz

risposta

10

La funzione finder.ngram_fd.viewitems() funziona

24

NLTK dotato di una propria bigrams generator, nonché una comoda funzione FreqDist().

f = open('a_text_file') 
raw = f.read() 

tokens = nltk.word_tokenize(raw) 

#Create your bigrams 
bgs = nltk.bigrams(tokens) 

#compute frequency distribution for all the bigrams in the text 
fdist = nltk.FreqDist(bgs) 
for k,v in fdist.items(): 
    print k,v 

Una volta ottenuto l'accesso al bigrammi e le distribuzioni di frequenza, è possibile filtrare in base alle proprie esigenze.

Spero che questo aiuti.

+0

Mi lascia con 'File" /usr/local/lib/python3.6/site-packages/nltk/util.py ", riga 467, in ngrams while n> 1: TypeError: '>' non supportato tra istanze di 'str' e 'int'' – m02ph3u5

0
from nltk import FreqDist 
from nltk.util import ngrams  
def compute_freq(): 
    textfile = open('corpus.txt','r') 

    bigramfdist = FreqDist() 
    threeramfdist = FreqDist() 

    for line in textfile: 
     if len(line) > 1: 
     tokens = line.strip().split(' ') 

     bigrams = ngrams(tokens, 2) 
     bigramfdist.update(bigrams) 
compute_freq() 
+0

basta inserire i rientri dopo' if '; il codice funziona se python 3.5 – Vahab

Problemi correlati