Creating a counter

Simon Kennedy sffjunkie at gmail.com
Thu Oct 16 09:44:09 EDT 2014


On Wednesday, 15 October 2014 19:39:43 UTC+1, Shiva  wrote:
> I am trying to search a string through files in a directory - however while
> Python script works on it and writes a log - I want to present the user with
> count of number of strings found. So it should increment for each string found.

You may ignore the following if you are just starting out on your Python learning odyssey but if you're past the early stages and looking to try something different then read on.

When you looked through the other answers and found a solution you're happy with that does not use the standard library you can look through the documentation and find a stdlib (https://docs.python.org/2.7/library/index.html) provided way that may be slightly more elegant for counting strings.

Something like the following ::

    >>> from collections import defaultdict
    >>> counter = defaultdict(int)
    >>> counter['string1'] += 1
    >>> counter['string2'] += 1
    >>> counter['string1'] += 1
    >>> print('Count string1={string1}, string2={string2}'.format(**counter), end='\r')
    Count string1=2, string2=1

https://docs.python.org/3/library/collections.html#collections.defaultdict

In the above code defaultdict is like a dictionary but if a key is not found then it uses the `int` factory parameter to add a value that is an integer with a value of 0  (which is what executing ``int()`` returns if you do it in the interactive Python prompt) for the dictionary key you're trying to access.

or ::

    >>> from collections import Counter
    >>> counter = Counter()
    >>> s = 'string1 string2 string1'
    >>> s.split()
    ['string1', 'string2', 'string1']
    >>> counter.update(s.split())
    >>> print('Count string1={string1}, string2={string2}'.format(**counter), end='\r')
    Count string1=2, string2=1

https://docs.python.org/2.7/library/collections.html#collections.Counter




More information about the Python-list mailing list