CSc 7003, Programming for Data Science (Summer 2020)
Program 1 - Histogram of Letter Counts
Write a Python program that counts the number of occurrences of the alphabetical letters in a text file and plots a histogram as follows:.
Here are couple of text files for you to test your program against:
Here is a program template:
import string #import sys def get_counts(fname): # this function takes the name of a file as input parameter, fname # it then reads the file into a string variable # then proceeds to process the string for the count of letters # answer should be returned in a list of 26 numbers def draw(counts): # this function takes as input the "counts" list # the function then proceeds to draw the histogram using matplotlib def main(): #counts = get_counts(sys.argv[1]) counts = get_counts("ra.txt") #print(counts) draw(counts) main()
NOTES:
- sys is a Python library that allows us to extract command line parameters. sys.argv[1] will contain the first command line parameter, sys.argv[2] the second and so on. If you run the program on a Terminal, you can use this method to read filename
- the Python commands to read from file into a string object is:
with open(fname) as f: data = f.read().lower()
- the string library contains useful functions such as
string.ascii_lowercase returns a string "abcdefghijklmnopqrstuvwxyz"
- Use the count(c) method to get the count of character c in a string
- Bar.py