首页 > 编程语言 > 详细

【python】collections的使用

时间:2018-09-10 16:48:21      阅读:211      评论:0      收藏:0      [点我收藏+]

老师布置了一个课后作业。

统计文本中字母出现的次数并找到最大的那一个

首先是读取文本吧。和c里的也差不多,打开,关闭,读取。

 1 path = YourPath 2 f = open(path) 3 f.close() 

 

然后就用到了这个黑科技。collections里的Counter。计数功能很强大。

代码:

 1 from collections import Counter
 2 
 3 path = YourPath
 4 f = open(path)
 5 lines = f.readlines()
 6 strs = []
 7 for line in lines:
 8 
 9     for i in line:
10         if i >= a and i <= z:
11             strs.append(i)
12         if i >= A and i <= Z:
13             strs.append(i)
14 #print(Counter(strs))
15 print(Counter(strs).most_common(1))
16 f.close()

导入模式如上图。Counter可以对list里的元素计数。并且有专门的方法调用返回最大值,并且默认返回最大值的值以最大值那个数。

常用操作:

 1 # 所有计数的总数
 2 sum(c.values())
 3 # 重置Counter对象,注意不是删除
 4 c.clear()
 5 # 将c中的键转为列表
 6 list(c)
 7 # 将c中的键转为set
 8 set(c)
 9 # 将c中的键值对转为字典
10 dict(c)  
11 #取出计数最多的n个元素
12 c.most_common(n)
13 # 取出计数最少的n-1个元素
14 c.most_common()[:-n:-1]
15 # 移除0和负值
16 c += Counter()  

 


 

有任何好的见解或者我有任何错误都请评论鸭qwq

【python】collections的使用

原文:https://www.cnblogs.com/Asumi/p/9620578.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!