从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)]热门推荐
1 带狗狗训练
4 听力训练狗狗
6 怎训练狗狗
7 腹肌训练狗狗
8 网球训练狗狗
9 记叙文训练狗狗
10 狗狗太凶怎么训练
11 核心力量训练狗狗
12 狗狗乱叫怎么训练
13 发音训练狗狗
14 怎么训练狗狗叼东西给主人
15 荆州训练狗狗
16 篮球训练狗狗
17 做训练狗狗
18 训练狗狗坐姿