In this tutorial, we will see how to get characters count in python where characters are reading from a file.

How to get Characters Count in Python:

Simple source code to get distinct characters count in a file.

File Content:

data.txt
I Love my country, make in India !

Get Characters Count in Python:

Reading each character from a file and counting each distinct character.

CharactersCount.py
document_text = open('data','r')
string = document_text.read().lower()
freq = [None] * len(string);
for i in range(0, len(string)):
    freq[i] = 1;
    for j in range(i+1, len(string)):
        if(string[i] == string[j]):
            freq[i] = freq[i] + 1;
            string = string[ : j] + '0' + string[j+1 : ];
print("Characters and their frequencies");
print("--------------------------------")
for i in range(0, len(freq)):
    if(string[i] != ' ' and string[i] != '0'):
        print(string[i] + "-> " + str(freq[i]));

Output:

Terminal
Characters and their frequencies
---------------------------------
i-> 4
l-> 1
o-> 2
v-> 1
e-> 2
m-> 2
y-> 2
c-> 1
u-> 1
n-> 3
t-> 1
r-> 1
,-> 1
a-> 2
k-> 1
d-> 1
!-> 1

Done!

Happy Learning 🙂