【问题标题】:N_gram frequency python NTLKBiggram 频率 python NLTK
【发布时间】:2020-02-08 03:56:08
【问题描述】:

我想编写一个函数来返回给定文本的 n-gram 中每个元素的频率。 请帮忙。 我做了这个代码来计算 2 克的频率

代码:

 from nltk import FreqDist
 from nltk.util import ngrams    
 def compute_freq():
     textfile = "please write a function"
     bigramfdist = FreqDist()
     threeramfdist = FreqDist()
     for line in textfile:
         if len(line) > 1:
             tokens = line.strip().split(' ')
             bigrams = ngrams(tokens, 2)
             bigramfdist.update(bigrams)
      return bigramfdist
  bigramfdist = compute_freq()

【问题讨论】:

  • 您在哪方面需要帮助?
  • 欢迎来到 StackOverflow。请花时间阅读这篇关于如何提供minimal, Complete, and Verifiable example 的帖子并相应地修改您的问题
  • 代码添加@yatu请看
  • @Code-Apprentice 我添加了我的代码,请看一下
  • 您的具体问题是什么?发布的代码如何无法执行您想要的操作?

标签: python pandas nltk tf-idf countvectorizer


【解决方案1】:

我没有看到预期的输出部分,因此我认为这是可能需要的。

import nltk

def compute_freq(sentence, n_value=2):

    tokens = nltk.word_tokenize(sentence)
    ngrams = nltk.ngrams(tokens, n_value)
    ngram_fdist = nltk.FreqDist(ngrams)
    return ngram_fdist

默认情况下,此函数返回二元组的频率分布 - 例如,

text = "This is an example sentence."
freq_dist = compute_freq(text)

现在,freq_dist 看起来像 -

FreqDist({('is', 'an'): 1, ('example', 'sentence'): 1, ('an', 'example'): 1, ('This', 
'is'): 1, ('sentence', '.'): 1})

从这里你可以像这样打印键和值

for k,v in freq_dist.items():
    print(k, v) 

('is', 'an') 1
('example', 'sentence') 1
('an', 'example') 1
('This', 'is') 1
('sentence', '.') 1

对于任何其他二元组,只需在调用函数时更改“n_value”参数。例如,

freq_dist = compute_freq(text, n_value=3) #will give you trigram distribution

('example', 'sentence', '.') 1
('an', 'example', 'sentence') 1
('This', 'is', 'an') 1
('is', 'an', 'example') 1

【讨论】:

    猜你喜欢
    • 2012-04-19
    • 2012-12-31
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-11-12
    • 1970-01-01
    相关资源
    最近更新 更多