Search code examples
pythonstringpunctuationdictionary-comprehension

Dictionary of punctuation counts for list of strings


How can I use dict comprehension to build a dictionary of punctuation counts for a list of strings? I was able to do it for a single string like this:

import string

test_string = "1990; and 1989', \ '1975/97', '618-907 CE"
counts = {p:test_string.count(p) for p in string.punctuation}

Edit: For anyone who may want this in the future, here's Patrick Artner's answer copied from below, with a very small modification to keep only punctuation counts:

# return punctuation Counter dict for string/list/pd.Series

import string
from collections import Counter
from itertools import chain

def count_punctuation(str_series_or_list):
    c = Counter(chain(*str_series_or_list))
    unwanted = set(c) - set(string.punctuation)
    for unwanted_key in unwanted: del c[unwanted_key]
    return c

Solution

  • Why count yourself?

    import string
    from collections import Counter
    
    
    test_string = "1990; and 1989', \ '1975/97', '618-907 CE"
    
    c = Counter(test_string)  # counts all occurences
    
    for p in string.punctuation:   # prints the one in string.punctuation
        print(p , c[p])            # access like dictionary (its a subclass of dict)
    print(c)
    

    Output:

    ! 0
    " 0
    # 0
    $ 0
    % 0
    & 0
    ' 4
    ( 0
    ) 0
    * 0
    + 0
    , 2
    - 1
    . 0
    / 1
    : 0
    ; 1
    < 0
    = 0
    > 0
    ? 0
    @ 0
    [ 0
    \ 1
    ] 0
    ^ 0
    _ 0
    ` 0
    { 0
    | 0
    } 0
    ~ 0
    Counter({'9': 7, ' ': 6, '1': 4, "'": 4, '7': 3, '0': 2, '8': 2, ',': 2, ';': 1, 'a': 1, 'n': 1, 'd': 1, '\\': 1, '5': 1, '/': 1, '6': 1, '-': 1, 'C': 1, 'E': 1})
    

    Counter is dictionary-like: see https://docs.python.org/2/library/collections.html#collections.Counter

    Edit: multiple strings in a list:

    import string
    from collections import Counter
    from itertools import chain
    
    test_strings = [ "1990; and 1989', \ '1975/97', '618-907 CE" , "someone... or no one? that's the question!", "No I am not!"]
    
    c = Counter(chain(*test_strings))
    
    for p in string.punctuation:
        print(p , c[p])
    
    print(c)
    

    Output: (removed 0-Entries)

    ! 2
    ' 5
    , 2
    - 1
    . 3
    / 1
    ; 1
    ? 1
    \ 1
    Counter({' ': 15, 'o': 8, '9': 7, 'n': 6, "'": 5, 'e': 5, 't': 5, '1': 4, 'a': 3, '7': 3, 's': 3, '.': 3, '0': 2, '8': 2, ',': 2, 'm': 2, 'h': 2, '!': 2, ';': 1, 'd': 1, '\\': 1, '5': 1, '/': 1, '6': 1, '-': 1, 'C': 1, 'E': 1, 'r': 1, '?': 1, 'q': 1, 'u': 1, 'i': 1, 'N': 1, 'I': 1})