Question

Python: Implement a function myIndex() that takes as input a text file and a list of...

Python:

Implement a function myIndex() that takes as input a text file and a list of words. Search the file and print the word along with the line numbers that word appears in the text as follows:

>>> myIndex('raven.txt', ['raven', 'mortal', 'dying', 'ghost', 'ghastly', 'evil', 'demon'])

raven     44, 53, 55, 64, 78, 97, 104, 111, 118, 120

mortal    30

dying     9

ghost     9

ghastly   82

evil      99, 106

demon     122

reven.txt:

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 named 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 darkness 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 above 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 further 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 sad soul 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 has 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 named Lenore -
Clasp a rare and radiant maiden, whom the angels named 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!

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

Program screenshot:

Sample output screenshot:

Code to copy:

# Create a function named myIndex().

# This function takes as input a text

# file and a list of words and print

# the word along with the line numbers

def myIndex(text_file, list_words):

    # Create a list to store the line number of the word

    list_line_number = []

    for word in list_words:

        list_line_number.append([])

   

    # Read the data in the file

    with open(text_file) as fp:       

        line = fp.readline()

        line_number = 1

       

        while line:

            line=line.replace(",", "")

            line=line.replace(".", "")

            line=line.replace("!", "")

            line=line.replace("'", " ")

            line=line.replace("\"", " ")

           

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

                # Create an if-statement to

                # check the word in the line

                if list_words[index] in line.split():

                    list_line_number[index].append(line_number)

           

           

            line = fp.readline()

            line_number += 1

    # Create a for-loop to display the line number list.

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

        print(list_words[index],end=" ")

        if list_line_number[index] == []:

            print("0")

        else:

            print(*list_line_number[index], sep = ", ")

Add a comment
Know the answer?
Add Answer to:
Python: Implement a function myIndex() that takes as input a text file and a list of...
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
  • Write a C/C++ program that reads a list of words and prints them in alphabetical order...

    Write a C/C++ program that reads a list of words and prints them in alphabetical order with one word per line. If two words have the same beginning sequence, the shorter word should be printed first. If the program is called with an “r” on the command line, the list of words should be printed in reverse alphabetical order. Test your program using the bunch-of-words.txt file bunch-of-words.txt: To Sherlock Holmes she is always the woman. I have seldom heard him...

  • Choose a symbol from either "The Gift of the Magi" and discuss what significance this symbol...

    Choose a symbol from either "The Gift of the Magi" and discuss what significance this symbol had to you as the reader (an example of this would be the combs Jim gave to Della and a discussion about a precious gift that you received or gave). Use text examples in this section. If someone were to write your life story, what symbol would be present and why?  How does this symbol represent you?   You can attach a picture of your symbol (an...

  • Help with Data Science python notebook, Question 1 Create a function called vowel_parse() that takes a...

    Help with Data Science python notebook, Question 1 Create a function called vowel_parse() that takes a single string as input. This string is the name of the input directory. It returns a dictionary. This dictionary has keys that are the names of the individual input files. The dictionary values are the number of words in that file that have adjacent vowels ('aa', 'ae', 'oo', 'ia', etc.). Use a regular expression to find these, do not hard code every possible combination...

  • english3

    In Moby-Dick, what does the gold coin symbolize for the crew?A. Ahab's fortune from his businessB. their reward for finding the whaleC. the Pequod's profits from whalingD. Ahab's wish to seem better than them Question 2 of 205.0 PointsThe following sentence from Self-Reliance is which type of figurative language? Society is a joint-stock companyA. descriptionB. synecdocheC. metaphorD. imagery Question 3 of 205.0 PointsWhich element of Thoreau's style is shown in these passages from Walden? Simplicity, simplicity, simplicity! I say, let...

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