File handling 18: Files and dictionary, Histogram, character frequency

# Write a program that creates a dictionary
# of the frequency of all characters in a file.
# display five most frequently occuring characters

# Files, Dictionary and Command line arguments
# Histogram - Character frequency

import sys
import operator

fname = sys.argv[1]
fs = open(fname, "r")

Char_freq = {}

while(True):
    Line = fs.readline().strip().lower()
   
    if not Line:
        break
   
    for ch in Line:
        if (ch.isalpha()):
            if ch in Char_freq:
                Char_freq[ch] += 1
            else:
                Char_freq[ch] = 1
           
for ch in Char_freq:
    print(ch, Char_freq[ch])

List1 = sorted(Char_freq.items(), key=operator.itemgetter(1), reverse=True)

print("Five most frequently occuring characters :")
for k,v in List1[0:5]:
    print(k,v)

fs.close()

No comments:

Post a Comment

Don't be a silent reader...
Leave your comments...

Anu