用好collections模块,对李白诗集进行字频统计

1、从一个计数问题开始

初学Python的人很可能会遇到字频统计这样的练习题,那么很容易会想到使用for循环来做,可是for循环的效率是很低的,而且会涉及到嵌套循环,代码及其冗余。

比如给定一个字符串,对字母进行计数统计:

Python is a popular programming language

一般会这样写:

my_str = "Python is a popular programming language"

def str_count(strs):
    '''对字符串进行字频统计,使用字典的get方法进行判断'''
    str_dict = {}
    for i in strs:
        str_dict[i] = str_dict.get(i,0) + 1
    return str_dict

str_count(my_str)

输出:

这次我们来介绍collection模块中的一个计数方法Counter,用它来计数操作可能只需一行代码。也由此学习一下Python中的内置模块-collections及它的强大功能。

如果使用Counter计数器来对上面那段字符串进行字频统计,就很简单:

from collections import Counter
my_str = "Python is a popular programming language"
Counter(my_str)

输出:

可以看到Counter计数器使用及其简单,只需要传入可迭代对象,就能统计每个元素的出现频次。

如果要对一篇文章,甚至一部小说进行字频统计,该怎么做呢?

以李白诗集为例,任务是统计所有字的频次,并找出出现频次最高的十个字。

这里你不妨先猜猜会有哪些字名列前十,话不多说放代码:

from collections import Counter

with open('李白.txt') as f:
    # 读取成列表
    c_list = f.readlines()
    
    # 所有诗整合成字符串
    c_str = ','.join(c_list)
    
    # 使用Counter进行字频统计
    c_cnt = Counter(c_str)
    
    # 去除符号、'李'、'白'等特殊字符
    useless_character = [',',',','。','【','】','\n','李','白']
    for i in useless_character:
        del c_cnt[i]
        
    # 使用most_common方法提取频次最高的前10字符
    c_top_10 = c_cnt.most_common(10)
    
    # 打印
    print(c_cnt)
    print(c_top_10)

输出:

出现频次最高的前十个字:

你猜中了几个呢?

2、聊聊Counter的其他用法

collections模块实现了特定目标的容器,来提供Python标准内建容器 dict、list、set、tuple 的替代选择。

也就是说collections模块是作为Python内建容器的补充,在很多方面它用起来更加有效率。

Counter是字典的子类,用于计数可哈希对象,计数元素像字典键(key)一样存储,它们的计数存储为值。

所以说Counter对象可以使用字典的所有方法。

创建Counter对象

from collections import Counter
 # 创建了一个空的Counter对象 
c = Counter()      
# 用可迭代对象创建了一个Counter对象
c = Counter('gallahad')    
 # 用映射来创建一个Counter
c = Counter({'red': 4, 'blue': 2})   
#用关键字参数创建Counter
c = Counter(cats=4, dogs=8)     

对可迭代对象进行计数

from collections import Counter
c = Counter('bananas')
c
# 输出:Counter({'b': 1, 'a': 3, 'n': 2, 's': 1})

根据键引用值

from collections import Counter
c = Counter('bananas')
c['a']
# 输出:3

如果不存在该键,则返回0

from collections import Counter
c = Counter('bananas')
c['u']
# 输出:0

删除其中一个键值对

from collections import Counter
c = Counter('bananas')
del c['a']
c
# 输出:Counter({'b': 1, 'n': 2, 's': 1})

用映射来创建一个Counter,并返回迭代器

from collections import Counter
c = Counter({'red': 3, 'blue': 1,'black':2})   
list(c.elements())
# 输出:['red', 'red', 'red', 'blue', 'black', 'black']

查看出现频次最高的前n元素及其次数

from collections import Counter
c = Counter('absabasdvdsavssaffsdaws')
c.most_common(3)
# 输出:[('s', 7), ('a', 6), ('d', 3)]

两个Counter相减

from collections import Counter
c = Counter(a=4, b=2, c=0)
d = Counter(a=1, b=2, c=3)
c.subtract(d)
c
# 输入:Counter({'a': 3, 'b': 0, 'c': -3})

转换成字典

from collections import Counter
c = Counter('bananas')
dict(c)
# 输出:{'b': 1, 'a': 3, 'n': 2, 's': 1}

添加可迭代对象

from collections import Counter
c = Counter('bananas')
c.update('apples')
c
# 输出:Counter({'b': 1, 'a': 4, 'n': 2, 's': 2, 'p': 2, 'l': 1, 'e': 1})

3、总结

Counter是字典的一个子类,它继承了字典的所有方法。

Counter作为计数器,使用简单高效。

键代表计数元素,值代表计数值。

most_common()方法用于排序,选取频次前n的键值对。

Counter对象可以进行加减运算及逻辑运算操作。

  • 2
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

@Python大数据分析

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值