In PYTHON please:
Write a function named word_stats that accepts as its parameter a string holding a file name, opens that file and reads its contents as a sequence of words, and produces a particular group of statistics about the input. You should report the total number of words (as an integer) and the average word length (as an un-rounded number). For example, suppose the file tobe.txt contains the following text:
To be or not to be, that is the question.
For the purposes of this problem, we will use whitespace to separate words. That means that some words include punctuation, as in "be,". For the input above, your function should produce exactly the following output. So the call of word_stats("tobe.txt") would produce the following console output:
Total words = 10 Average length = 3.2
Assumptions: You may assume that the input file exists and is readable.
Here is the Python code:
def word_stats (filename):
lst = []
with open (filename, "r") as fp:
while True:
s =fp.readline ()
if s == "":
break
lst.extend (s.split())
print (lst)
wordlengths = [len (word) for word in lst]
print ("Total words = " + str(len(lst)) + " Average length = " + str (sum(wordlengths) / len(wordlengths)))
if __name__ == "__main__":
filename = input ("Please enter the file name: ")
word_stats (filename)
Get Answers For Free
Most questions answered within 1 hours.