collections模块的使用

 1. Counter

  counter是collections中的一个模块, 它能够统计出字符串/文本中的每一个元素出现的次数, 并可以对结果进行进一步的处理.

  使用方法

  传入: 字符串

  默认返回: Counter对象的字典

text = """
Django is a high-level Python Web 
framework that encourages rapid 
development and clean, pragmatic design. 
Built by experienced developers, 
it takes care of much of the hassle of Web development, 
so you can focus on writing your app without needing to reinvent the wheel. 
It’s free and open source.
"""
from collections import Counter
c = Counter(text.replace(" ", ""))
print(c)

  默认不调用任何方法时会返回每一个元素出现的次数, 并以键值对的方式返回, {元素, 次数}, 返回的结果按照元素出现的次数从大到小依次排序

  

most_common()方法
from collections import Counter
c = Counter(text.replace(" ", "")).most_common(3)
print(c)
# [('e', 37), ('o', 19), ('n', 18)]
most_common()接受一个int类型, 用来从结果中将前三个元素的同级结果输出, 返回的是一个真正的列表

.elements()方法
c = Counter(A=4, Y=2, Q=1)
print(c.elements())
# <itertools.chain object at 0x00000000021BA0B8>  返回的是一个可迭代对象
print(list(c.elements()))
# ['A', 'A', 'A', 'A', 'Y', 'Y', 'Q']   按照你指定的个数重复字符串
 
 
 

  

原文地址:https://www.cnblogs.com/594504110python/p/9709492.html