从Python数据集中找到k个最常见的单词

如果需要在数据集中找到10个最常见的单词,python可以使用collections模块帮助我们找到它。集合模块具有一个计数器类,该计数器类在提供单词列表之后给出单词的计数。我们还使用most_common方法找出程序输入所需的此类单词的数量。

例子

在下面的示例中,我们采用一个段落,然后首先创建Apply的单词列表split()。然后,我们将应用counter()来查找所有单词的计数。最后,most_common函数将为我们提供我们想要的频率最高的此类单词的适当结果。

from collections import Counter
word_set = " This is a series of strings to count " \
   "many words . They sometime hurt and words sometime inspire "\
   "Also sometime fewer words convey more meaning than a bag of words "\
   "Be careful what you speak or what you write or even what you think of. "\
# Create list of all the words in the string
word_list = word_set.split()

# Get the count of each word.
word_count = Counter(word_list)

# Use most_common() method from Counter subclass
print(word_count.most_common(3))

输出结果

运行上面的代码给我们以下结果-

[('words', 4), ('sometime', 3), ('what', 3)]