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

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.
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
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 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
Write a python program that can solve system of linear equations in three variables using input...
Write a python program that can solve system of linear equations in three variables using input function. Paste your program in a word document or notepad. Note that I am using pycharm. please use a not really complex codes, thanks
Using Python, create a program that will act as a number convertor. This program will convert...
Using Python, create a program that will act as a number convertor. This program will convert an input decimal integer into binary and hexadecimal formats. a) Define a main function named numberconvertor(). Inside the main function, write all the logic of your code. [5% marks] b) Looping indefinitely (Hint: use infinite while loop), the program should give the user the 3 options given below and allow the user to select one among them. [15% marks] 1. converting a decimal number...
How to do this in Python (using Lists): Create a python program that allows a user...
How to do this in Python (using Lists): Create a python program that allows a user to display, sort and update as needed a List of U.S States containing the State Capital and State Bird. You will need to embed the State data into your Python code. The user interface will allow the user to perform the following functions: 1. Display all U.S. States in Alphabetical order along with Capital and Bird 2. Search for a specific state and display...
Write a Python program that has the user enter their name.   Using the user's name calculate...
Write a Python program that has the user enter their name.   Using the user's name calculate the following: 1. How many letters are in the user's name? 2. Print the user's name in REVERSE both in capital letters and lowercase letters 3. Print the ASCII value for each letter of the user's name. 4. Print the SUM of all of the letters of the user's name (add each letter from #3)
Using Python Write a program that does the following in order: 1.     Asks the user to enter...
Using Python Write a program that does the following in order: 1.     Asks the user to enter a name 2.     Asks the user to enter a number “gross income” 3.     Asks the user to enter a number “state tax rate” 4.     Calculates the “Federal Tax”, “FICA tax” and “State tax” 5.     Calculates the “estimated tax” and round the value to 2 decimal places 6.     Prints values for “name”, “gross income” and “estimated tax” The program should contain three additional variables to store the Federal tax, FICA...
Using Python write a program that does the following in order: 1. Ask user to enter...
Using Python write a program that does the following in order: 1. Ask user to enter a name 2. Ask the user to enter five numbers “amount1”, “amount2”, “amount3”, “amount4”, “amount5” 3. Calculate the sum of the numbers “amount1”, “amount2”, “amount3”, “amount4”, “amount5” 4. If the sum is greater than 0, print out the sum 5. If the sum is equal to zero, print out “Your account balance is zero” 6. If the sum is less than 0, print out...
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT