Counting Letter Frequency in a String (Python)

后端 未结 12 2107
既然无缘
既然无缘 2020-12-01 17:52

I am trying to count the occurrences of each letter of a word

word = input(\"Enter a word\")

Alphabet=[\'a\',\'b\',\'c\',\'d\',\'e\',\'f\',\'g\',\'h\',\'i\'         


        
12条回答
  •  無奈伤痛
    2020-12-01 18:16

    If using libraries or built-in functions is to be avoided then the following code may help:

    s = "aaabbc"  # sample string
    dict_counter = {}  # empty dict for holding characters as keys and count as values
    for char in s:  # traversing the whole string character by character
        if not dict_counter or char not in dict_counter.keys():  # Checking whether the dict is
            # empty or contains the character
            dict_counter.update({char: 1})  # if not then adding the character to dict with count = 1
        elif char in dict_counter.keys():  # if the char is already in the dict then update count
            dict_counter[char] += 1
    for key, val in dict_counter.items(): # Looping over each key and value pair for printing
        print(key, val)
    

    Output:
    a 3
    b 2
    c 1

提交回复
热议问题