【问题标题】:counting n-gram frequency in python nltk在python nltk中计算n-gram频率
【发布时间】:2012-12-31 03:31:34
【问题描述】:

我有以下代码。我知道我可以使用apply_freq_filter 函数来过滤掉少于频率计数的搭配。但是,在我决定为过滤设置什么频率之前,我不知道如何获取文档中所有 n-gram 元组(在我的情况下为 bi-gram)的频率。如您所见,我使用的是 nltk collocations 类。

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)

【问题讨论】:

  • 你试过finder.ngram_fd.viewitems()吗?
  • 感谢 finder.ngram_fd.viewitems() 工作!

标签: python nltk n-gram


【解决方案1】:

我尝试了以上所有方法并找到了一个更简单的解决方案。 NLTK 带有一个简单的最常见的频率 Ngram。

filtered_sentence 是我的单词标记

import nltk
from nltk.util import ngrams
from nltk.collocations import BigramCollocationFinder
from nltk.metrics import BigramAssocMeasures

word_fd = nltk.FreqDist(filtered_sentence)
bigram_fd = nltk.FreqDist(nltk.bigrams(filtered_sentence))

bigram_fd.most_common()

这应该给出如下输出:

[(('working', 'hours'), 31),
 (('9', 'hours'), 14),
 (('place', 'work'), 13),
 (('reduce', 'working'), 11),
 (('improve', 'experience'), 9)]

【讨论】:

    【解决方案2】:
    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()
    

    【讨论】:

    • 只在'if'之后插入缩进;如果 python 3.5 则代码有效
    【解决方案3】:

    NLTK 带有自己的bigrams generator,以及方便的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
    

    一旦您可以访问 BiGram 和频率分布,您就可以根据需要进行过滤。

    希望对您有所帮助。

    【讨论】:

    • 这给我留下了File "/usr/local/lib/python3.6/site-packages/nltk/util.py", line 467, in ngrams while n > 1: TypeError: '>' not supported between instances of 'str' and 'int'
    【解决方案4】:

    finder.ngram_fd.viewitems() 函数有效

    【讨论】:

    • 似乎已弃用,但您可以使用 finder.ngram_fd[('this', 'bigram')] 获取二元组的频率
    猜你喜欢
    • 1970-01-01
    • 2019-10-20
    • 1970-01-01
    • 2011-11-27
    • 2019-01-31
    • 2018-03-16
    • 1970-01-01
    • 2020-02-08
    • 2020-02-11
    相关资源
    最近更新 更多