6.27 At the end of this and other textbooks, there usually is an index that lists the pages where a certain word appears. In this problem, you will create an index for a text but, instead of page number, you will use the line numbers. You will implement function index() that takes as input the name of a text file and a list of words. For every word in the list, your function will find the lines in the text file where the word occurs and print the corresponding line numbers (where the numbering starts at 1). You should open and read the file only once.
>>> index('raven.txt', ['raven', 'mortal', 'dying', 'ghost', File: raven.txt 'ghastly', 'evil','demon'])
ghost 9
dying 9
demon 122
evil 99, 106
ghastly 82
mortal 30
raven 44, 53, 55, 64, 78, 97, 104, 111, 118, 120
def index(filename, wordList):
#created a dictionary with key as words to be indexed and value
as a list of line nums
wordCount={}
#creating a key value pair for each word
for word in wordList:
wordCount[word]=[]
lineCount=0
#reading the file line by line
for line in open(filename):
lineCount=lineCount+1
#splitting the line into a list for proper searching
words=line.split()
for word in wordList:
if word in words:
wordCount[word].append(str(lineCount))
for word in wordCount:
lineNums=",".join(wordCount[word])
print ("%s : %s")%(word,lineNums)
index("raven.txt",['raven','dead','mortal','grave','ghost'])
sample output:
I have created a file named raven.txt and got this output
you can use your own raven.txt and word of list
ghost : 2
mortal :
grave : 6
dead : 3,6
raven : 4,5
-----------‐------------------------
Please give me a UPVOTE. Thank you ?.
Get Answers For Free
Most questions answered within 1 hours.