Question

Your task is to process a file containing the text of a book available as a...

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: 42761

The number of words is: 7078

The number of occurrences of War is: 4

The number of occurrences of Peace is: 2

The number of occurrences of Power is: 11

0 0
Add a comment Improve this question Transcribed image text
Answer #1

In case of any query do comment. Please rate answer as well. Thanks

Note: I have used arbitrary file with general text. You should use your file as input.

Code:

#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)

Input file used:

main.py constitution.txt 1 this is a test for war including peace in to generate power 2 power is again a illustrated enemy o

Screen shot of the code for indentation and Output:

ovou pw main.py constitution.txt 1 #function to count number of characters, words in agiven file and returns a list of words

Add a comment
Know the answer?
Add Answer to:
Your task is to process a file containing the text of a book available as a...
Your Answer:

Post as a guest

Your Name:

What's your source?

Earn Coins

Coins can be redeemed for fabulous gifts.

Not the answer you're looking for? Ask your own homework help question. Our experts will answer your question WITHIN MINUTES for Free.
Similar Homework Help Questions
  • Sample program run - Needs to be coded in python -Enter the text that you want to search for, Or DONE when finished: val...

    Sample program run - Needs to be coded in python -Enter the text that you want to search for, Or DONE when finished: valiant paris The valiant Paris seeks for his love. -Enter the text that you want to search for, or DONE when finished: Romeo and Juliet Enter Romeo and Juliet aloft, at the WIndow -- Enter the text that you want to search for, DONE when finished: DONE   # copy the following two lines into any # program...

  • Write a C program to run on ocelot to read a text file and print it...

    Write a C program to run on ocelot to read a text file and print it to the display. It should optionally find the count of the number of words in the file, and/or find the number of occurrences of a substring, and/or take all the words in the string and sort them lexicographically (ASCII order). You must use getopt to parse the command line. There is no user input while this program is running. Usage: mywords [-cs] [-f substring]...

  • Basic Python code needed Define the get_lines_from_file) function which is passed a filename as a parameter....

    Basic Python code needed Define the get_lines_from_file) function which is passed a filename as a parameter. The function reads the information from the file (corresponding to the filename parameter) and returns a list of strings where each element of the returned list corresponds to one line of the file. The list of strings which is returned by the function should not contain any newline characters. For example, if the file contains the text: 10 440 240 4 42 4 42...

  • QUESTION17 The following Python script aims to read lines from a text file and add them...

    QUESTION17 The following Python script aims to read lines from a text file and add them to a list Marlout oft. 00 Example P Flag question If the text file contains the following lines wordt wordz words the list will be ['word, word2, Words' after the execution of the program Question: Rearrange the following statements on the correct (logical) form Note: The-indicates the indentation #--> Program infile=onen/fileName --infile = open(fileName, 'r') . . -try: --for line in infile: --infile =...

  • Using Python, if you could help me with the code # Create a modified version of the search linear function defined # above to return all # occurrences of the search word in the text # An occurrence is...

    Using Python, if you could help me with the code # Create a modified version of the search linear function defined # above to return all # occurrences of the search word in the text # An occurrence is the index of a word in the text that matches your given # search string. # e.g. if "hatter" occurs at positions 0, 6, 12 then return [ 0, 6, 12] def search_linear_occurrences(xs, target): """ Find and return a list of...

  • (Count the occurrences of words in a text file) Rewrite Listing 21.9 to read the text...

    (Count the occurrences of words in a text file) Rewrite Listing 21.9 to read the text from a text file. The text file is passed as a command-line argument. Words are delimited by white space characters, punctuation marks (, ; . : ?), quotation marks (' "), and parentheses. Count the words in a case-sensitive fashion (e.g., consider Good and good to be the same word). The words must start with a letter. Display the output of words in alphabetical...

  • C++ Lab 1. Read in the contents of a text file up to a maximum of...

    C++ Lab 1. Read in the contents of a text file up to a maximum of 1024 words – you create your own input. When reading the file contents, you can discard words that are single characters to avoid symbols, special characters, etc. 2. Sort the words read in ascending order in an array (you are not allowed to use Vectors) using the Selection Sort algorithm implemented in its own function. 3. Search any item input by user in your...

  • Write a Python function makeDict() that takes a filename as a parameter. The file contains DNA...

    Write a Python function makeDict() that takes a filename as a parameter. The file contains DNA sequences in Fasta format, for example: >human ATACA >mouse AAAAAACT The function returns a dictionary of key:value pairs, where the key is the taxon name and the valus is the total number of 'A' and 'T' occurrences. For example, for if the file contains the data from the example above the function should return: {'human':4,'mouse':7}

  • (Python 3) Write a program that reads the contents of a text file. The program should...

    (Python 3) Write a program that reads the contents of a text file. The program should then create a dictionary in which the keys are individual words found in the file and the values are the number of times each word appears and a list that contains the line numbers in the file where the word (the key) is found. Then the program will create another text file. The file should contain an alphabetical listing of the words that are...

  • Many word processing programs allow the user to view properties of the text contained therein. For...

    Many word processing programs allow the user to view properties of the text contained therein. For this problem, your task is to write a Python function that reads a text file and computes the total number of words and characters in the file. The function has been started for you in the file wordcount.py. Modify this code as indicated and include the file in your homework submission. Print (do not return any outputs) the statistics so that is looks identical...

ADVERTISEMENT
Free Homework Help App
Download From Google Play
Scan Your Homework
to Get Instant Free Answers
Need Online Homework Help?
Ask a Question
Get Answers For Free
Most questions answered within 3 hours.
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT