使用 Python 从数据集中找出 k 个最常出现的单词

pythonserver side programmingprogramming更新于 2025/9/22 12:28:17

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

示例

在下面的例子中,我们取一个段落,然后首先应用 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. "\
# 创建字符串中所有单词的列表
word_list = word_set.split()

# 获取每个单词的计数。
word_count = Counter(word_list)

# 使用 Counter 子类中的 most_common() 方法
print(word_count.most_common(3))

输出

运行上述代码得到以下结果 −

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

相关文章


有用资源