1.统计列表中元素频次前4的数据(使用collections.Counter)
from collections import Counter
from random import randint
data = [randint(0,10) for _ in range(20)] # 推导表达式+随机数生成序列
print(data) # [0, 9, 8, 9, 8, 2, 3, 2, 9, 9, 5, 5, 8, 5, 10, 10, 10, 9, 8, 1]
data = Counter(data) # 进行元素频次统计
print(data) # Counter({9: 5, 8: 4, 5: 3, 10: 3, 2: 2, 0: 1, 3: 1, 1: 1})
print(data.most_common(4)) # 排名前4的值 [(9, 5), (8, 4), (5, 3), (10, 3)]
2.统计英文文本中频次前10的单词
import re # 正则
from collections import Counter
with open('word.txt',encoding="utf-8") as f: # 从文件中读取英文文章,with 会自动关闭IO流
wordStr = f.read() # 读取文件中所有内容
# print(wordStr)
wordList = re.split('\W+',wordStr) # 非单词组合分割字符串
# print(wordList)
wordCount = Counter(wordList)
print(wordCount.most_common(10)) # [('you', 32), ('to', 19), ('who', 10), ('those', 9), ('the', 8), ('and', 7), ('have', 7), ('that', 6), ('want', 6), ('make', 6)]