Question

In: Computer Science

Using python what is needed to be added or changed Problem 1: The program has three...

Using python

what is needed to be added or changed

Problem 1:

The program has three functions in it.

  1. I’ve written all of break_into_list_of_words()--DO NOT CHANGE THIS ONE. All it does is break the very long poem into a list of individual words. Some of what it's doing will not make much sense to you until we get to the strings chapter, and that's fine--that's part of why I wrote it for you. :)
  2. There’s a main() which you’ll add a little bit to, but it should stay pretty small -- some print statements and some function calls
  3. There’s a definition of a function called count_how_many_words(), which takes two arguments. (Don’t change the arguments.) You’ll write the entire block for this.
    1. Note: My return statement is definitely not what you want; it’s just there so that the program runs when I give it to you. You will want to change what the function returns!

I want you to complete the count_how_many_words() function, and then call it (multiple times) inside main() to find out how many times Poe used the word “Raven” (or “raven”) and how many times he used “Nevermore” (or “nevermore”) inside the poem “The Raven.” You may not use list.count().

Don’t add any global variables or constants (besides the one I’ve declared, which could be moved into main() but would be even uglier there).

Example output (with incorrect numbers):

The word "Raven" (or "raven") appears 42 times in Edgar Allen Poe's "The Raven."

The word "Nevermore" (or "nevermore") appears 48 times in Edgar Allen Poe's "The Raven."

# this is what quick-and-dirty data cleaning looks like, friends

def break_into_list_of_words(string):

    """takes a long string and returns a list of all of the words in the string"""

    # vvv YOU DO NOT HAVE TO CHANGE ANYTHING IN HERE vvv

    list_of_words = []

    # break by newlines to get a list of lines

    list_of_lines = string.split('\n')

    # remove the empty lines

    while '' in list_of_lines:

        list_of_lines.remove('')

    # split the line up

    for line in list_of_lines:

        # we have a few words run together with dashes

        # this breaks the line up by dashes (non-ideal, but eh)

        maybe_broken_line = line.split('—')

        # now we will take the line that might be split, and we'll split again

        # but this time on spaces

        for a_line in maybe_broken_line:

            list_of_words = list_of_words + a_line.split(' ')

    # if blank spaces crept in (they did), let's get rid of them

    while ' ' in list_of_words:

        list_of_words.remove(' ')

    while '' in list_of_words:

        list_of_words.remove('')

    # removing a lot of unnecessary punctuation; gives you more options

    # for how to solve this problem

    # (you'll get a cleaner way to do this, later in the semester, too)

    for index in range(0, len(list_of_words)):

        list_of_words[index] = list_of_words[index].strip(";")

        list_of_words[index] = list_of_words[index].strip("?")

        list_of_words[index] = list_of_words[index].strip(".")

        list_of_words[index] = list_of_words[index].strip(",")

        list_of_words[index] = list_of_words[index].strip("!")

        # smart quotes will ruin your LIFE

        list_of_words[index] = list_of_words[index].strip("“")

        list_of_words[index] = list_of_words[index].strip("”")

        list_of_words[index] = list_of_words[index].strip("’")

        list_of_words[index] = list_of_words[index].strip("‘")

    # all we have now is a list with words without punctuation

    # (secretly, some words still have apostrophes and dashes in 'em)

    # (but we don't care)

    return list_of_words

    # ^^^ YOU DO NOT HAVE TO CHANGE ANYTHING IN HERE ^^^

# this is the function you'll add a lot of logic to

def count_how_many_words(word_list, counting_string):

    """takes in a string and a list and returns the number of times that string occurs in the list"""

    return None # this is just here so the program still compiles

def main():

    count = 0

    words = break_into_list_of_words(THE_RAVEN)

    # a reasonable first step, to see what you've got:

    # for word in words:

    #     print(word, end = " ")

if __name__ == "__main__":

    main()

Solutions

Expert Solution

Here is the Python code. I read in the raven poem from a file called raven.txt, change that if you need to. Needed to do this because otherwise THE_RAVEN shows up undefined.

# this is what quick-and-dirty data cleaning looks like, friends
def break_into_list_of_words(string):
    """takes a long string and returns a list of all of the words in the string"""
    # vvv YOU DO NOT HAVE TO CHANGE ANYTHING IN HERE vvv
    list_of_words = []
    # break by newlines to get a list of lines
    list_of_lines = string.split('\n')
    # remove the empty lines
    while '' in list_of_lines:
        list_of_lines.remove('')
    # split the line up
    for line in list_of_lines:
        # we have a few words run together with dashes
        # this breaks the line up by dashes (non-ideal, but eh)
        maybe_broken_line = line.split('—')
        # now we will take the line that might be split, and we'll split again
        # but this time on spaces
        for a_line in maybe_broken_line:
            list_of_words = list_of_words + a_line.split(' ')
    # if blank spaces crept in (they did), let's get rid of them
    while ' ' in list_of_words:
        list_of_words.remove(' ')
    while '' in list_of_words:
        list_of_words.remove('')
    # removing a lot of unnecessary punctuation; gives you more options
    # for how to solve this problem
    # (you'll get a cleaner way to do this, later in the semester, too)

    for index in range(0, len(list_of_words)):
        list_of_words[index] = list_of_words[index].strip(";")
        list_of_words[index] = list_of_words[index].strip("?")
        list_of_words[index] = list_of_words[index].strip(".")
        list_of_words[index] = list_of_words[index].strip(",")
        list_of_words[index] = list_of_words[index].strip("!")

        # smart quotes will ruin your LIFE
        list_of_words[index] = list_of_words[index].strip("“")
        list_of_words[index] = list_of_words[index].strip("”")
        list_of_words[index] = list_of_words[index].strip("’")
        list_of_words[index] = list_of_words[index].strip("‘")

    # all we have now is a list with words without punctuation
    # (secretly, some words still have apostrophes and dashes in 'em)
    # (but we don't care)

    return list_of_words

    # ^^^ YOU DO NOT HAVE TO CHANGE ANYTHING IN HERE ^^^
# this is the function you'll add a lot of logic to

def count_how_many_words(word_list, counting_string):
    """takes in a string and a list and returns the number of times that string occurs in the list"""
    counting_string = counting_string.lower ()
    counter = 0
    for word in word_list:
        if word.strip(".',’ -").lower () == counting_string:
            counter+= 1
    
    return counter

def main():
    f = open ("raven.txt")
    THE_RAVEN = f.read ()
    f.close ()
    
    count = 0
    words = break_into_list_of_words(THE_RAVEN)
    
    s = "Raven"
    s2 = s.lower ()
    c =count_how_many_words (words, s)
    print ("The word ""{0}"" (or ""{1}"") appears {2} times in Edgar Allen Poe's ""The Raven.""".format(s, s2, c))

    s = 'Nevermore'
    s2 = s.lower ()
    c =count_how_many_words (words, s)
    print ("The word ""{0}"" (or ""{1}"") appears {2} times in Edgar Allen Poe's ""The Raven.""".format(s, s2, c))

if __name__ == "__main__":
    main()

Related Solutions

Python Problem Problem 1: In this problem you are asked to write a Python program to...
Python Problem Problem 1: In this problem you are asked to write a Python program to find the greatest and smallest elements in the list. The user gives the size of the list and its elements (positive and negative integers) as the input. Sample Output: Enter size of the list: 7 Enter element: 2 Enter element: 3 Enter element: 4 Enter element: 6 Enter element: 8 Enter element: 10 Enter element: 12 Greatest element in the list is: 12 Smallest...
Using LIST and FUNCTION Write a program in Python that asks for the names of three...
Using LIST and FUNCTION Write a program in Python that asks for the names of three runners and the time it took each of them to finish a race. The program should display who came in first, second, and third place.
Question(on Python). There is a Python program what could solve the simple slide puzzles problem by...
Question(on Python). There is a Python program what could solve the simple slide puzzles problem by A* algorithm. Please fill in the body of the a_star() function. In order to solve a specific problem, the a_star function needs to know the problem's start state, the desired goal state, and a function that expands a given node. To be precise, this function receives as its input the current state and the goal state and returns a list of pairs of the...
Write a Python program in a file called consonants.py, to solve the following problem using a...
Write a Python program in a file called consonants.py, to solve the following problem using a nested loop. For each input word, replace each consonant in the word with a question mark (?). Your program should print the original word and a count of the number of consonants replaced. Assume that the number of words to be processed is not known, hence a sentinel value (maybe "zzz") should be used. Sample input/output: Please enter a word or zzz to quit:...
Python - Rewriting a Program Rewrite Program 1 using functions. The required functions are in the...
Python - Rewriting a Program Rewrite Program 1 using functions. The required functions are in the table below. Create a Python program that will calculate the user’s net pay based on the tax bracket he/she is in. Your program will prompt the user for their first name, last name, their monthly gross pay, and the number of dependents. The number of dependents will determine which tax bracket the user ends up in. The tax bracket is as follows: 0 –...
Program must be in Python Write a program in Python whose inputs are three integers, and...
Program must be in Python Write a program in Python whose inputs are three integers, and whose output is the smallest of the three values. Input is 7 15 3
PYTHON Program Problem Statement: Write a Python program that processes information related to a rectangle and...
PYTHON Program Problem Statement: Write a Python program that processes information related to a rectangle and prints/displays the computed values. The program will behave as in the following example. Note that in the two lines, Enter length and Enter width, the program does not display 10.0 or 8.0. They are values typed in by the user and read in by the program. The first two lines are text displayed by the program informing the user what the program does. This...
Write a Python program to solve the 8-puzzle problem (and its natural generalizations) using the A*...
Write a Python program to solve the 8-puzzle problem (and its natural generalizations) using the A* search algorithm. The problem. The 8-puzzle problem is a puzzle invented and popularized by Noyes Palmer Chapman in the 1870s. It is played on a 3-by-3 grid with 8 square blocks labeled 1 through 8 and a blank square. Your goal is to rearrange the blocks so that they are in order, using as few moves as possible. You are permitted to slide blocks...
Using Python Programming PROBLEM 3 - OLD MACDONALD: Write a program to print the lyrics of...
Using Python Programming PROBLEM 3 - OLD MACDONALD: Write a program to print the lyrics of the song ”Old MacDonald”. Your program should print the lyrics using five different animals (i.e., cow, sheep, dog, cat ,turkey) using the example verse below. For this problem you are required to write then make use of a function getVerse that takes two string parameters: (1) the name of an animal and (2) the sound that animal makes. The function should not print anything...
Using the Python program: a/ Write a program that adds all numbers from 1 to 100...
Using the Python program: a/ Write a program that adds all numbers from 1 to 100 to a list (in order). Then remove the multiples of 3 from the list. Print the remaining values. b/ Write a program that initializes a list with ten random integers from 1 to 100. Then remove the multiples of 3 and 5 from the list. Print the remaining values. Please show your work and explain. Thanks
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT