python - 从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 个单词。但是需要绘制最常见的单词组合。
解决方案
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})
推荐阅读
- php - 根据 CodeIgniter 中数据透视表中的类别 ID 显示帖子
- ansible - mysql_replication_role 是默认的还是用户定义的?如果用户定义,我如何在我的剧本中设置它?
- python - 某些字符的正则表达式冲突 (ISO-8859-1 Windows-1252)
- java - 如何在java中解析(分离结构和值)json格式字符串
- chatbot - 仅使用一种意图的意图识别
- git - 如何删除历史 git commit
- javascript - JavaScript-选择其他选择的选项时,请从多个选择框中隐藏选项
- html - 选择框的自定义滚动条
- ios - 测试因 fastlane 中的错误而失败
- mysql - 无法运行/执行 MySQL 触发器