龙空技术网

一日一技:用python实现最常用单词计数

Python编程之美 112

前言:

此时你们对“python统计单词”大体比较关注,大家都想要知道一些“python统计单词”的相关资讯。那么小编也在网上搜集了一些有关“python统计单词””的相关资讯,希望咱们能喜欢,姐妹们一起来学习一下吧!

python学习

用python实现最常用单词计数

如果需要在字符串中找到10个最常见的单词,我们可以使用python的collections模块来实现它。

collections模块具有一个Counter类,该类提供单词列表之后给出单词的计数。

另外,我们还可以使用most_common方法找出程序输入所需的此类单词的数量。

下面,我们直接举例:

在下面的示例中,我们首先创建一个使用split()的单词列表。 然后,我们将应用counter()方法来查找所有单词的计数。

最后,most_common函数将为我们实现频率最高单词的结果。

from collections import Counterword_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)print(word_count.most_common(3))

输出结果:

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

你学会了吗?

欢迎大家留言,一起讨论学习,

谢谢关注!

标签: #python统计单词