python3 50个练习例子之统计序列中元素的出现频率

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)]


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值