Python中collections.Counter模块的most_comm方法小示例

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/Jerry_1126/article/details/85109382

collections模块中的Counter方法可以对列表和字符串进行计数,设置可以对字典中的键和值进行处理(dict.keys(), dict.items(),dict.values()),其中有个不错的方法most_common,可以用来统计列表或字符串中最常出现的元素。比如说,要统计下面的字符串某个字母个数前三的显示出来,就可以使用most_common(3),来处理,其中的3代表最常用的3个。

Life doesn't just happen to you; you receive everything in your life based on what you've given.

具体代码:

>>> from collections import Counter
>>> s="Life doesn't just happen to you; you receive everything in your life based on what you've given."
>>> import re
>>> Counter(re.sub(r"[ |']+", "", s)).most_common(3)   # 将空格,单引号用''替换
[('e', 12), ('o', 7), ('i', 6)]
>>>

从上面的代码可以看出,可以很简单的看出出现次数最大的字母: e, o, i,分别居于前三位。

猜你喜欢

转载自blog.csdn.net/Jerry_1126/article/details/85109382
今日推荐