簡體   English   中英

計算詞和詞組頻率的Python nltk

[英]Python nltk counting word and phrase frequency

我正在使用NLTK並嘗試將單詞短語計數到特定文檔的某個長度以及每個短語的頻率。 我將字符串標記為獲取數據列表。

from nltk.util import ngrams
from nltk.tokenize import sent_tokenize, word_tokenize
from nltk.collocations import *


data = ["this", "is", "not", "a", "test", "this", "is", "real", "not", "a", "test", "this", "is", "this", "is", "real", "not", "a", "test"]

bigrams = ngrams(data, 2)

bigrams_c = {}
for b in bigrams:
    if b not in bigrams_c:
        bigrams_c[b] = 1
    else:
        bigrams_c[b] += 1

上面的代碼給出和輸出如下:

(('is', 'this'), 1)
(('test', 'this'), 2)
(('a', 'test'), 3)
(('this', 'is'), 4)
(('is', 'not'), 1)
(('real', 'not'), 2)
(('is', 'real'), 2)
(('not', 'a'), 3)

這是我正在尋找的部分內容。

我的問題是,是否有更方便的方法來說明長度為4或5的短語而不重復此代碼只更改計數變量?

既然你標記了這個nltk ,下面是如何使用nltk的方法來實現它,這些方法比標准python集合中的方法有更多的功能。

from nltk import ngrams, FreqDist
all_counts = dict()
for size in 2, 3, 4, 5:
    all_counts[size] = FreqDist(ngrams(data, size))

字典all_counts每個元素都是ngram頻率的字典。 例如,您可以獲得五個最常見的三元組:

all_counts[3].most_common(5)

是的,不要運行這個循環,使用collections.Counter(bigrams) pandas.Series(bigrams).value_counts() collections.Counter(bigrams)pandas.Series(bigrams).value_counts()來計算pandas.Series(bigrams).value_counts()的計數。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM