The class Counter
basically iterates on the string and with each character it increases the value in the dictionary:
texto = 'anderson carlos woss'
quantidade = {}
for caractere in texto:
quantidade[caractere] = quantidade.get(caractere, 0) + 1
print(quantidade)
# {'a': 2, 'n': 2, 'd': 1, 'e': 1, 'r': 2, 's': 4, 'o': 3, ' ': 2, 'c': 1, 'l': 1, 'w': 1}
In fact, the class Counter
is a specialization of dict
using the method update
:
class Counter(dict):
def __init__(self, iterable=None, **kwds):
'''Create a new, empty Counter object. And if given, count elements
from an input iterable. Or, initialize the count from another mapping
of elements to their counts.
>>> c = Counter() # a new, empty counter
>>> c = Counter('gallahad') # a new counter from an iterable
>>> c = Counter({'a': 4, 'b': 2}) # a new counter from a mapping
>>> c = Counter(a=4, b=2) # a new counter from keyword args
'''
self.update(iterable, **kwds)
The method update
is superscripted by the class as:
def update(self, iterable=None, **kwds):
if iterable is not None:
if isinstance(iterable, Mapping):
if self:
self_get = self.get
for elem, count in iterable.iteritems():
self[elem] = self_get(elem, 0) + count
else:
dict.update(self, iterable) # fast path when counter is empty
else:
self_get = self.get
for elem in iterable:
self[elem] = self_get(elem, 0) + 1
if kwds:
self.update(kwds)
Which, quite simply, is what I originally presented.
To return the items in frequency order, just check the method implementation most_common
:
def most_common(self, n=None):
if n is None:
return sorted(self.iteritems(), key=_itemgetter(1), reverse=True)
return _heapq.nlargest(n, self.iteritems(), key=_itemgetter(1))
That is, just use the function sorted
.
All source code of the class can be seen in https://svn.python.org/projects/python/trunk/Lib/collections.py
Knows the
collections.Counter
?– Woss
But I wanted to learn the code of this library
– Lucas Oliveira
So please edit your question and be clearer in what you want. You don’t need to save words to describe your problem and your goal, as well as the difficulties you are facing. I also invite you to do the [tour] and read the [Ask] guide first of all.
– Woss
Anderson has to summarize the code that the library uses to solve this problem ?
– Lucas Oliveira