如何统计序列中元素的出现频度?
案例1:
方法一:传统方法
from random import randint
# 随机生成一个列表
data = [randint(0, 20) for _ in range(30)]
# 以列表中的值为字典的键,0为字典的值建立字典
c = dict.fromkeys(data, 0)
# 依次遍历列表,遇到一个元素,就把字典中对应的键的值加1
for x in data:
c[x] += 1
print(c)
方法二:使用 collections.Counter 对象
将序列传入 Counter 的构造器,得到 Counter 对象是元素频率的字典
Counter.most_common(n) 方法得到频率最高的 n 个元素的列表
from random import randint
from collections import Counter
# 随机生成一个列表
data = [randint(0, 20) for _ in range(30)]
c = Conuiter(data)
# 得到的 c 就是一个collections.Counter类型的数据,和方法 一 结果一样
# 用法与字典一样,例如 c[2] , 就是得到 键为2 对应的值
print(c)
# 另外,还可以使用 most_common() 方法得到 出现频率最高的几个键和值
print(c.most_common(3)) # 输出前3名
案例2:
from collections import Counter
import re
with open('./text.txt', 'r') as f:
txt = f.read()
# 使用 正则表达式 对文本进行切割,按照 非字母字符 进行切割
l1 = re.split('\W+', txt)
c = Conuiter(li)
# 得到频率最高的10个单词
print(c.most_common(10))