Python Program to Count Character Frequency in String

In this program, we first read string from user and then we create dictionary with character as key and its frequency count as value. And, finally key and value as count are displayed from dictionary.


This Python program calculates number of occurrence of each character in the string given by user.


Python Source Code: Find Character Frequency


# Frequency of each character in string

# Get string from user
string = input("Enter some text: ")

# Set frequency as empty dictionary
frequency_dict = {}

for character in string:
    if character in frequency_dict:
        frequency_dict[character] += 1
    else:
        frequency_dict[character] = 1

# Displaying result
print("\n--------------------------")
print("Character\tFrequency")
print("--------------------------")
for character, frequency in frequency_dict.items():
    print("%5c\t\t%5d" %(character, frequency))

Output

Now lets check correctness of our program for the longest word in English: pneumonoultramicroscopicsilicovolcanoconiosis

Enter some text: pneumonoultramicroscopicsilicovolcanoconiosis

--------------------------
Character	Frequency
--------------------------
    p		    2
    n		    4
    e		    1
    u		    2
    m		    2
    o		    9
    l		    3
    t		    1
    r		    2
    a		    2
    i		    6
    c		    6
    s		    4
    v		    1