liczenie częstotliwości n-gram w Pythonie nltk

Mam następujący kod. Wiem, że mogę użyć funkcji apply_freq_filter do filtrowania kolokacji, które są mniejsze niż liczba częstotliwości. Jednak nie wiem, jak uzyskać częstotliwości wszystkich krotek n-gramowych (w moim przypadku bi-gram) w dokumencie, zanim zdecyduję, jaką częstotliwość ustawić do filtrowania. Jak widać używam klasy kolokacji 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)
Author: Rkz, 2013-01-16

3 answers

NLTK posiada własną bigrams generator, a także wygodną funkcję 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

Gdy będziesz miał dostęp do Bigramów i rozkładów częstotliwości, możesz filtrować zgodnie z własnymi potrzebami.

Mam nadzieję, że to pomoże.
 26
Author: Ram Narasimhan,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2013-11-15 18:25:03

Funkcja finder.ngram_fd.viewitems() działa

 10
Author: Rkz,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2013-01-21 01:22:09
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
Author: Vahab,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2018-03-08 18:02:56