首页 > 解决方案 > 从python中的消息列表中查找最常见的词对

问题描述

我有一个包含 100 条消息的列表。而且我能够找到消息列表中使用最频繁的单词。但我想找到最常出现的一对单词。例如,key 和 board 被显示为最常用的词。但我需要找到在 NLTK 中将“键盘”用作一对的出现次数。这里的摘要是句子的列表,而抽象词是词的列表。

abstracts = [preprocessing(document) for document in abstracts]

abstract_words = " ".join(abstracts)
abstract_words = abstract_words.split()

def plot_word_frequency(words, top_n=10):
    word_freq = FreqDist(words)
    labels = [element[0] for element in word_freq.most_common(top_n)]
    counts = [element[1] for element in word_freq.most_common(top_n)]
    plot = sns.barplot(labels, counts)
    return plot

plot_word_frequency(abstract_words, 10)

在这里,我可以绘制单个前 10 个单词。但是需要绘制最常见的单词组合。

标签: pythonnltk

解决方案


N-grams,见python 中的 n-grams,四、五、六克?,例如

>>> from collections import Counter
>>> from nltk import ngrams
>>> tokens = "this is a sentence with some of this words this is meh ".split()
>>> Counter(list(ngrams(tokens, 2)))
Counter({('this', 'is'): 2, ('is', 'a'): 1, ('a', 'sentence'): 1, ('sentence', 'with'): 1, ('with', 'some'): 1, ('some', 'of'): 1, ('of', 'this'): 1, ('this', 'words'): 1, ('words', 'this'): 1, ('is', 'meh'): 1})

推荐阅读