CSc 7003, Programming for Data Science (Summer 2021)

Program 2 - 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:

lipogram.txt

ra.txt

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:

  1. 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
  2. the Python commands to read from file into a string object is:
      with open(fname) as f:
        data = f.read().lower()
    
  3. the string library contains useful functions such as
      string.ascii_lowercase returns a string "abcdefghijklmnopqrstuvwxyz"
    
  4. Use the count(c) method to get the count of character c in a string
  5. Bar.py