In the above Python program to count the number of each character in a text file, need to import two libraries and then open() method will open the file name in read only mode and built-in functions will count each character in the text file.
import collections
import pprint
file_input = input('Enter File Name: ')
with open(file_input, 'r') as info:
count = collections.Counter(info.read().upper())
value = pprint.pformat(count)
print(value)
Sample Output:
Enter File Name: sample.txt
Counter({' ': 106,
'E': 95,
'T': 50,
'A': 49,
'R': 49,
'I': 49,
'N': 42,
'S': 38,
'H': 30,
'L': 22,
'C': 22,
'U': 21,
'D': 20,
'G': 19,
'O': 19,
'M': 16,
'P': 12,
'B': 10,
'V': 9,
'F': 7,
'.': 7,
'0': 6,
'Y': 6,
'W': 5,
'1': 5,
'-': 4,
',': 4,
'’': 3,
'(': 3,
')': 3,
'\n': 3,
'8': 2,
'5': 2,
'9': 2,
'"': 2,
'2': 1,
'3': 1,
'6': 1,
'Q': 1})