In: Computer Science
Write a function getStats(fname) that determines the following
statistics for the input file,
fname, and write the results to the text file, FileStats.txt.
• Number of occurrences of each day of the week in the file.
• Number of lines (determined by end of line character “\n”)
• Number of words
• Numbers of characters (excludes spaces between words)
The output from getStats() should
• print the message ‘To view the results go to FileStats.txt’
• return ‘Thanks for using the getStats() function’
Include the name of the file and your name in the first line of
FileStats.txt. For example,
I ran getStats(“Emma.txt”) and got the following results:
The problem does not specify which programming language to use, so have used Python. Below is the code:
def getStats (fname):
with open (fname) as f:
contents = f.read ()
daysofweek = ['Monday', 'Tuesday', 'Wednesday', 'Thursday',
'Friday', 'Saturday', 'Sunday']
dayscount = []
for day in daysofweek:
dayscount.append (contents.lower().count(day.lower()))
nlines = contents.count ('\n')
nwords = len (contents.split ())
nchars = len (''.join (contents.split() ) )
with open ("FileStats.txt", 'w') as f:
i = 0
for day in daysofweek:
s = "Number of occurrences of " + day + " is " + str(dayscount [i])
+ "\n"
f.write (s)
i += 1
f.write ("The number of lines is " + str (nlines) + "\n")
f.write ("The number of words is " + str (nwords) + "\n")
f.write ("The number of characters is " + str (nchars) +
"\n")
print ('To view the results, go to FileStats.txt')
return 'Thanks for using the getStats () function'
print (getStats ("D:\greatexpectations.txt"))
##### Below is a sample run of the code:
To view the results, go to FileStats.txt Thanks for using the getStats () function
##### Below are the contents of FileStats.txt (run on the novel Great Expectations as a text file):
Number of occurrences of Monday is 19
Number of occurrences of Tuesday is 5
Number of occurrences of Wednesday is 8
Number of occurrences of Thursday is 3
Number of occurrences of Friday is 1
Number of occurrences of Saturday is 9
Number of occurrences of Sunday is 33
The number of lines is 8233
The number of words is 187594
The number of characters is 821753