18.1k views
5 votes
1. Your task is to process a file containing the text of a book available as a file as follows:A function GetGoing(filename) that will take a file name as a parameter. The function will read the contents of the file into a string. Then it prints the number of characters and the number of words in the file. The function also returns the content of the file as a Python list of words in the text file.A function FindMatches(keywordlist, textlist): The parameter keywordlist contains a list of words. The parameter textlist contains text from a book as a list of words. For each word in keywordlist, the function will print the number of times it occurs in textlist. Nothing is returned.If you implemented the functions correctly then the following program:booktext = GetGoing('constitution.txt') FindMatches (['War', 'Peace', 'Power'], booktext) Will read the file "constitution.txt" and print something like the following:The number of characters is: 42761The number of words is: 7078The number of occurrences of War is: 4The number of occurrences of Peace is: 2The number of occurrences of Power is: 11

1 Answer

6 votes

Answer:

See explaination

Step-by-step explanation:

#function to count number of characters, words in a given file and returns a list of words

def GetGoing(filename):

file = open(filename)

numbrOfCharacters =0

numberOfWords = 0

WordList = []

#iterate over file line by line

for line in file:

#split the line into words

words = line.strip().split()

#add counn of words to numberOfWords

numberOfWords = numberOfWords + len(words)

#find number of characters in each word and add it to numbrOfCharacters

numbrOfCharacters = numbrOfCharacters + sum(len(word) for word in words)

#append each word from a line to WordList

for word in words:

WordList.append(word)

#display the result

print("The number of characters: ", numbrOfCharacters)

print("The number of Words: ", numberOfWords)

#return the list of words

return WordList

#find matches for keywords given in textlist

def FindMatches(keywordlist, textlist):

for keyword in keywordlist:

keyword = keyword.lower()

print ("The number of occurrences of {} is: {}".format(keyword,len([i for i, s in enumerate(textlist) if s == keyword])))

#main

booktext = GetGoing("constitution.txt")

FindMatches (['War', 'Peace', 'Power'], booktext)

User Eleandro Duzentos
by
5.0k points