案例一:在某随机序例中,找到出现频度最高的3个元素,它们出现的次数是多少?

 from random import randint
# 利用列表解析器生成随机序列,包含有30个元素
data = [randint(0, 20) for _ in range(30)]
# 以data中的元素作为字典的键,以0作为值创建一个字典
my_dict = dict.fromkeys(data,0)
# 对序列data进行迭代循环
for x in data:
my_dict[x] += 1 # 对迭代的每个元素在其相对应的键值上加1
# 对字典进行排序,按倒序排列
result = sorted(my_dict.items(), key=lambda x: x[1], reverse=True)
# 输出出现频度最高的三个元素
print(result[:3]

在 python 中还有一种更简便有效的方法,那就是使用 collections.Counter 对象。将序列传入Counter 的构造器,得到的 Counter 对象是包含元素频度的字典,Counter.most_common(n) 方法得到频度最高的 n 个元素的列表。

from collections import Counter
...
# 将序列data作为Counter的构造参数
counter = Counter(data)
# 将3作为参数传给Counter.most_common()
result = counter.most_common(3)
# 输出结果,即出现频度最高的三个元素和次数
print(result)

案例二:对某英文文章的单词进行词频统计,找到出现频度最高的10个单词,它们出现的次数是多少?

 import re
from collections import Counter # 要处理的文本
txt = '''
Beautiful is better than ugly.
Explicit is better than implicit.
Simple is better than complex.
Complex is better than complicated.
Flat is better than nested.
Sparse is better than dense.
Readability counts.
Special cases aren't special enough to break the rules.
Although practicality beats purity.
Errors should never pass silently.
Unless explicitly silenced.
In the face of ambiguity, refuse the temptation to guess.
There should be one-- and preferably only one --obvious way to do it.
Although that way may not be obvious at first unless you're Dutch.
Now is better than never.
Although never is often better than *right* now.
If the implementation is hard to explain, it's a bad idea.
If the implementation is easy to explain, it may be a good idea.
Namespaces are one honking great idea -- let's do more of those!
'''
# 用正则表达式拆分单词
words = re.split('\W+', txt)
# 将列表作为参数传给Counter构造函数
counter = Counter(words)
# 找到10个出现频度最高的单词
result = counter.most_common(10)
# 输出出现频度最高的10个单词和它们出现的次数
print(result)

输出结果:

python 学习笔记(四) 统计序列中元素出现的频度(即次数)-LMLPHP

04-26 19:58