Count characters within a string in Python [closed]

-2

I have a small function that counts occurrence of characters in a string. It works for me in some places, but not in others. Specifically in Jupyter is not going well and I do not know the reason. Thanks.

def char_frequency(str1):
dict = {}
for n in str1:
    keys = dict.keys()
if n in keys:
     dict[n] += 1
else:
    dict[n] = 1
return dict
    
asked by Noob 15.08.2018 в 11:43
source

1 answer

0

I guess you just want to know how many characters are in the string and store them in a dictionary where the key is the character and the value is the number of times it appears:

def char_frequency(str1):
    res = dict()
    for caracter in str1:
        if caracter in res.keys():
            res[caracter] = res[caracter] + 1
        else:
            res[caracter] = 1
    return res

Another more elegant option would be to use the library collections

from collections import Counter
p = "Hola me llamo Pepe"
print(Counter(p))

This returns:

Counter({'l': 3, ' ': 3, 'e': 3, 'o': 2, 'a': 2, 'm': 2, 'H': 1, 'P': 1, 'p': 1})
    
answered by 15.08.2018 / 13:45
source