Question

In: Computer Science

Problem 1: python For the first problem of this homework, we’re going to try something a...

Problem 1: python

For the first problem of this homework, we’re going to try something a little different. I’ve created the start of a file, which you’ll edit to finish the assignment: count_words_in_the_raven.py

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."

# a constant
THE_RAVEN = '''
Once upon a midnight dreary, while I pondered, weak and weary,
Over many a quaint and curious volume of forgotten lore—
While I nodded, nearly napping, suddenly there came a tapping,
As of some one gently rapping, rapping at my chamber door.
“’Tis some visitor,” I muttered, “tapping at my chamber door—
Only this and nothing more.”

Ah, distinctly I remember it was in the bleak December;
And each separate dying ember wrought its ghost upon the floor.
Eagerly I wished the morrow;—vainly I had sought to borrow
From my books surcease of sorrow—sorrow for the lost Lenore—
For the rare and radiant maiden whom the angels name Lenore—
Nameless here for evermore.

And the silken, sad, uncertain rustling of each purple curtain
Thrilled me—filled me with fantastic terrors never felt before;
So that now, to still the beating of my heart, I stood repeating
“’Tis some visitor entreating entrance at my chamber door—
Some late visitor entreating entrance at my chamber door;—
This it is and nothing more.”

Presently my soul grew stronger; hesitating then no longer,
“Sir,” said I, “or Madam, truly your forgiveness I implore;
But the fact is I was napping, and so gently you came rapping,
And so faintly you came tapping, tapping at my chamber door,
That I scarce was sure I heard you”—here I opened wide the door;—
Darkness there and nothing more.

Deep into that darkness peering, long I stood there wondering, fearing,
Doubting, dreaming dreams no mortal ever dared to dream before;
But the silence was unbroken, and the stillness gave no token,
And the only word there spoken was the whispered word, “Lenore?”
This I whispered, and an echo murmured back the word, “Lenore!”—
Merely this and nothing more.

Back into the chamber turning, all my soul within me burning,
Soon again I heard a tapping somewhat louder than before.
“Surely,” said I, “surely that is something at my window lattice;
Let me see, then, what thereat is, and this mystery explore—
Let my heart be still a moment and this mystery explore;—
’Tis the wind and nothing more!”

Open here I flung the shutter, when, with many a flirt and flutter,
In there stepped a stately Raven of the saintly days of yore;
Not the least obeisance made he; not a minute stopped or stayed he;
But, with mien of lord or lady, perched above my chamber door—
Perched upon a bust of Pallas just above my chamber door—
Perched, and sat, and nothing more.

Then this ebony bird beguiling my sad fancy into smiling,
By the grave and stern decorum of the countenance it wore,
“Though thy crest be shorn and shaven, thou,” I said, “art sure no craven,
Ghastly grim and ancient Raven wandering from the Nightly shore—
Tell me what thy lordly name is on the Night’s Plutonian shore!”
Quoth the Raven “Nevermore.”

Much I marvelled this ungainly fowl to hear discourse so plainly,
Though its answer little meaning—little relevancy bore;
For we cannot help agreeing that no living human being
Ever yet was blessed with seeing bird above his chamber door—
Bird or beast upon the sculptured bust above his chamber door,
With such name as “Nevermore.”

But the Raven, sitting lonely on the placid bust, spoke only
That one word, as if his soul in that one word he did outpour.
Nothing farther then he uttered—not a feather then he fluttered—
Till I scarcely more than muttered “Other friends have flown before—
On the morrow he will leave me, as my Hopes have flown before.”
Then the bird said “Nevermore.”

Startled at the stillness broken by reply so aptly spoken,
“Doubtless,” said I, “what it utters is its only stock and store
Caught from some unhappy master whom unmerciful Disaster
Followed fast and followed faster till his songs one burden bore—
Till the dirges of his Hope that melancholy burden bore
Of ‘Never—nevermore’.”

But the Raven still beguiling all my fancy into smiling,
Straight I wheeled a cushioned seat in front of bird, and bust and door;
Then, upon the velvet sinking, I betook myself to linking
Fancy unto fancy, thinking what this ominous bird of yore—
What this grim, ungainly, ghastly, gaunt, and ominous bird of yore
Meant in croaking “Nevermore.”

This I sat engaged in guessing, but no syllable expressing
To the fowl whose fiery eyes now burned into my bosom’s core;
This and more I sat divining, with my head at ease reclining
On the cushion’s velvet lining that the lamp-light gloated o’er,
But whose velvet-violet lining with the lamp-light gloating o’er,
She shall press, ah, nevermore!

Then, methought, the air grew denser, perfumed from an unseen censer
Swung by Seraphim whose foot-falls tinkled on the tufted floor.
“Wretch,” I cried, “thy God hath lent thee—by these angels he hath sent thee
Respite—respite and nepenthe from thy memories of Lenore;
Quaff, oh quaff this kind nepenthe and forget this lost Lenore!”
Quoth the Raven “Nevermore.”

“Prophet!” said I, “thing of evil!—prophet still, if bird or devil!—
Whether Tempter sent, or whether tempest tossed thee here ashore,
Desolate yet all undaunted, on this desert land enchanted—
On this home by Horror haunted—tell me truly, I implore—
Is there—is there balm in Gilead?—tell me—tell me, I implore!”
Quoth the Raven “Nevermore.”

“Prophet!” said I, “thing of evil!—prophet still, if bird or devil!
By that Heaven that bends above us—by that God we both adore—
Tell this soul with sorrow laden if, within the distant Aidenn,
It shall clasp a sainted maiden whom the angels name Lenore—
Clasp a rare and radiant maiden whom the angels name Lenore.”
Quoth the Raven “Nevermore.”

“Be that word our sign of parting, bird or fiend!” I shrieked, upstarting—
“Get thee back into the tempest and the Night’s Plutonian shore!
Leave no black plume as a token of that lie thy soul hath spoken!
Leave my loneliness unbroken!—quit the bust above my door!
Take thy beak from out my heart, and take thy form from off my door!”
Quoth the Raven “Nevermore.”

And the Raven, never flitting, still is sitting, still is sitting
On the pallid bust of Pallas just above my chamber door;
And his eyes have all the seeming of a demon’s that is dreaming,
And the lamp-light o’er him streaming throws his shadow on the floor;
And my soul from out that shadow that lies floating on the floor
Shall be lifted—nevermore!'''


# 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("!")
# 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(".")
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

import re
def break_into_list_of_words(string):
    list_of_words = []
    list_of_lines = string.split('\n')
    w='''"'''
    while w in list_of_lines:
        list_of_lines.remove(w)
    for line in list_of_lines:
        maybe_broken_line = line.split('—')
    for a_line in list_of_lines:
        list_of_words = list_of_words + re.split(r'[‘!”?“;.’—,\s]\s*', a_line)
    while '' in list_of_words:
        list_of_words.remove('')
    while '' in list_of_words:
        list_of_words.remove('')
    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("“")
        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("’")
    return list_of_words
THE_RAVEN='''Once upon a midnight dreary, while I pondered, weak and weary,
Over many a quaint and curious volume of forgotten lore—
While I nodded, nearly napping, suddenly there came a tapping,
As of some one gently rapping, rapping at my chamber door.
“’Tis some visitor,” I muttered, “tapping at my chamber door—
Only this and nothing more.”

Ah, distinctly I remember it was in the bleak December;
And each separate dying ember wrought its ghost upon the floor.
Eagerly I wished the morrow;—vainly I had sought to borrow
From my books surcease of sorrow—sorrow for the lost Lenore—
For the rare and radiant maiden whom the angels name Lenore—
Nameless here for evermore.

And the silken, sad, uncertain rustling of each purple curtain
Thrilled me—filled me with fantastic terrors never felt before;
So that now, to still the beating of my heart, I stood repeating
“’Tis some visitor entreating entrance at my chamber door—
Some late visitor entreating entrance at my chamber door;—
This it is and nothing more.”

Presently my soul grew stronger; hesitating then no longer,
“Sir,” said I, “or Madam, truly your forgiveness I implore;
But the fact is I was napping, and so gently you came rapping,
And so faintly you came tapping, tapping at my chamber door,
That I scarce was sure I heard you”—here I opened wide the door;—
Darkness there and nothing more.

Deep into that darkness peering, long I stood there wondering, fearing,
Doubting, dreaming dreams no mortal ever dared to dream before;
But the silence was unbroken, and the stillness gave no token,
And the only word there spoken was the whispered word, “Lenore?”
This I whispered, and an echo murmured back the word, “Lenore!”—
Merely this and nothing more.

Back into the chamber turning, all my soul within me burning,
Soon again I heard a tapping somewhat louder than before.
“Surely,” said I, “surely that is something at my window lattice;
Let me see, then, what thereat is, and this mystery explore—
Let my heart be still a moment and this mystery explore;—
’Tis the wind and nothing more!”

Open here I flung the shutter, when, with many a flirt and flutter,
In there stepped a stately Raven of the saintly days of yore;
Not the least obeisance made he; not a minute stopped or stayed he;
But, with mien of lord or lady, perched above my chamber door—
Perched upon a bust of Pallas just above my chamber door—
Perched, and sat, and nothing more.

Then this ebony bird beguiling my sad fancy into smiling,
By the grave and stern decorum of the countenance it wore,
“Though thy crest be shorn and shaven, thou,” I said, “art sure no craven,
Ghastly grim and ancient Raven wandering from the Nightly shore—
Tell me what thy lordly name is on the Night’s Plutonian shore!”
Quoth the Raven “Nevermore.”

Much I marvelled this ungainly fowl to hear discourse so plainly,
Though its answer little meaning—little relevancy bore;
For we cannot help agreeing that no living human being
Ever yet was blessed with seeing bird above his chamber door—
Bird or beast upon the sculptured bust above his chamber door,
With such name as “Nevermore.”

But the Raven, sitting lonely on the placid bust, spoke only
That one word, as if his soul in that one word he did outpour.
Nothing farther then he uttered—not a feather then he fluttered—
Till I scarcely more than muttered “Other friends have flown before—
On the morrow he will leave me, as my Hopes have flown before.”
Then the bird said “Nevermore.”

Startled at the stillness broken by reply so aptly spoken,
“Doubtless,” said I, “what it utters is its only stock and store
Caught from some unhappy master whom unmerciful Disaster
Followed fast and followed faster till his songs one burden bore—
Till the dirges of his Hope that melancholy burden bore
Of ‘Never—nevermore’.”

But the Raven still beguiling all my fancy into smiling,
Straight I wheeled a cushioned seat in front of bird, and bust and door;
Then, upon the velvet sinking, I betook myself to linking
Fancy unto fancy, thinking what this ominous bird of yore—
What this grim, ungainly, ghastly, gaunt, and ominous bird of yore
Meant in croaking “Nevermore.”

This I sat engaged in guessing, but no syllable expressing
To the fowl whose fiery eyes now burned into my bosom’s core;
This and more I sat divining, with my head at ease reclining
On the cushion’s velvet lining that the lamp-light gloated o’er,
But whose velvet-violet lining with the lamp-light gloating o’er,
She shall press, ah, nevermore!

Then, methought, the air grew denser, perfumed from an unseen censer
Swung by Seraphim whose foot-falls tinkled on the tufted floor.
“Wretch,” I cried, “thy God hath lent thee—by these angels he hath sent thee
Respite—respite and nepenthe from thy memories of Lenore;
Quaff, oh quaff this kind nepenthe and forget this lost Lenore!”
Quoth the Raven “Nevermore.”

“Prophet!” said I, “thing of evil!—prophet still, if bird or devil!—
Whether Tempter sent, or whether tempest tossed thee here ashore,
Desolate yet all undaunted, on this desert land enchanted—
On this home by Horror haunted—tell me truly, I implore—
Is there—is there balm in Gilead?—tell me—tell me, I implore!”
Quoth the Raven “Nevermore.”

“Prophet!” said I, “thing of evil!—prophet still, if bird or devil!
By that Heaven that bends above us—by that God we both adore—
Tell this soul with sorrow laden if, within the distant Aidenn,
It shall clasp a sainted maiden whom the angels name Lenore—
Clasp a rare and radiant maiden whom the angels name Lenore.”
Quoth the Raven “Nevermore.”

“Be that word our sign of parting, bird or fiend!” I shrieked, upstarting—
“Get thee back into the tempest and the Night’s Plutonian shore!
Leave no black plume as a token of that lie thy soul hath spoken!
Leave my loneliness unbroken!—quit the bust above my door!
Take thy beak from out my heart, and take thy form from off my door!”
Quoth the Raven “Nevermore.”

And the Raven, never flitting, still is sitting, still is sitting
On the pallid bust of Pallas just above my chamber door;
And his eyes have all the seeming of a demon’s that is dreaming,
And the lamp-light o’er him streaming throws his shadow on the floor;
And my soul from out that shadow that lies floating on the floor
Shall be lifted—nevermore!''' 
def count_how_many_words(word_list, counting_string):
    count=0;
    for i in word_list:
        if(i.upper()==counting_string.upper()):
            count=count+1
    return count;
def main():
    words = break_into_list_of_words(THE_RAVEN)
    for word in words:
        print(word, end = " ")
    search1="Raven"
    search2="Nevermore"
    print(count_how_many_words(word, search1))
    print('''\nThe word "'''+search1+'''"(or '''+search1.lower()+'''") appears '''+str(count_how_many_words(words, search1))+''' times in Edgar Allen Poe's "The Raven."''')
    print('''\nThe word "'''+search2+'''"(or '''+search2.lower()+'''") appears '''+str(count_how_many_words(words, search2))+''' times in Edgar Allen Poe's "The Raven."''')
if __name__ == "__main__":
    main()

Thank you! if you have any queries post it below in the comment section I will try my best to resolve your queries and I will add it to my answer if required. Please give upvote if you like it.


Related Solutions

Part 1. We’re going to titrate formic acid with the strong base, NaOH. There is initially...
Part 1. We’re going to titrate formic acid with the strong base, NaOH. There is initially 100. mL of 0.50 M formic acid and the concentration of NaOH is 1.0 M. All work must be shown to receive credit 7) What is the pOH at the equivalence point? ___________ 8) If, instead of NaOH being added, 0.05 moles of HCl is added by    bubbling the gas through the solution. Assume that the volume has not changed. What is the...
According to Aristotle, if we’re not motivated by something of intrinsic value, our choices are irrational....
According to Aristotle, if we’re not motivated by something of intrinsic value, our choices are irrational. Why does he think this? Is he right? In your answer give an example of something Aristotle takes to have intrinsic value. OR If we are to apply virtue ethics to businesses, we need to identify flourishing, virtues, and vices for a business. What characteristics would a flourishing business have? What are two virtues for businesses? What are the vices of deficiency and excess...
According to Aristotle, if we’re not motivated by something of intrinsic value, our choices are irrational....
According to Aristotle, if we’re not motivated by something of intrinsic value, our choices are irrational. Why does he think this? Is he right? In your answer give an example of something Aristotle takes to have intrinsic value.
The following question examines the prices of televisions. In this question, we’re going to consider regressions...
The following question examines the prices of televisions. In this question, we’re going to consider regressions of the form: pricei = β0 + β1sizei + β2size2i + β3UHDi + εi Where pricei is the retail price of the television in dollars, sizei is the size of the TV screen in inches, and UHDi is a binary {0,1} indictor for whether or not the television supports ultra-high definition (versus conventional high definition). We run the regression two different ways. The coefficients...
We’re going to titrate formic acid with the strong base, NaOH. There is initially 100. mL...
We’re going to titrate formic acid with the strong base, NaOH. There is initially 100. mL of 0.50 M formic acid and the concentration of NaOH is 1.0 M. All work MUST be shown to receive credit. See announcement for due date. a) What is the initial pH of the formic acid solution?​​​___________ b) What is the percent ionization under initial conditions? ​​​__________% c) After the addition of 10 mL of NaOH, what is the pH? ​​        ___________ d)...
We’re going to think about other possible sources for magnetic fields. Recall that the source of...
We’re going to think about other possible sources for magnetic fields. Recall that the source of magnetic fields in permanent magnets is aligned electron orbits(electrons going in circles all the same direction so the circles are parallel and they are either all traveling clockwise or counter clockwise). Where do electric fields come from? Draw an electric field diagram for each of the two types of source. Pick a spot in one of your field diagrams. How would you determine the...
We’re going to titrate formic acid with the strong base, NaOH. There is initially 100. mL...
We’re going to titrate formic acid with the strong base, NaOH. There is initially 100. mL of 0.50 M formic acid and the concentration of NaOH is 1.0 M. A. What is the initial pH of the formic acid solution? B. What is the percent ionization under initial conditions? C. After the addition of 10 mL of NaOH, what is the pH? D. After the addition of 25 mL of NaOH, what is the pH? Think about where in the...
3.1 Probabilities are a “likelihood” that something is going to happen. It is not a certainty....
3.1 Probabilities are a “likelihood” that something is going to happen. It is not a certainty. How does this type of statistic help us when conducting research in criminal justice? How does it hurt the process? Find an example online to back your response.
Homework 1 Python basics and flow control Given August 26th – Due September 8th In this...
Homework 1 Python basics and flow control Given August 26th – Due September 8th In this assignment you have to develop a security program. Inside a while loop you will ask several security questions. Be creative! When all of them are answered correctly a piece of secret information will be printed and the program will be finished. In your program: - use at least 1 time each of the following functions: print(), input(), len(), str(), int(), float() and randint(). -...
Homework problem to study for quiz Friday. 1. The # of units to be produced annually:...
Homework problem to study for quiz Friday. 1. The # of units to be produced annually: 200,000 tins Direct labor: 1 hour per 100 tins Variable overhead costs per direct labor hour: Indirect materials amount to $2.05 Indirect labor $1.20 Utilities $9.25 Maintenance $3.50 Fixed overhead costs per quarter: Insurance $3,000 Depreciation $2,000 Rent $12,000 a. Calculate the budgeted total manufacturing overhead for the year. b. Sales are 60,000 tins per quarter Variable costs per dollar of sales: sales commissions...
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT