Could someone please provide the code for both of these prob

Could someone please provide the code for both of these problems in PYTHON 3 please?

FIRST PART:

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.

File: raven.txt

>>> index(\'raven.txt\', [\'raven\', \'mortal\', \'dying\', \'ghost\',

\'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

SECOND PART:

The first input argument of function index() in Part one is supposed to be the

name of a text file. If the file cannot be found by the interpreter or if it cannot be read as a

text file, an exception will be raised. Reimplement function index() so that the message

shown here is printed instead:

>>> index(\'rven.txt\', [\'raven\', \'mortal\', \'dying\', \'ghost\'])

File \'rven.txt\' not found.

Solution

def index(name,wlist):
   try:
       f = open(name)
   except (OSError, IOError):
       print(\"File \'\",name,\"\' not found.\",sep=\'\')
       return
   di = {}
   count = 0
   for l in f.readlines():
       count = count+1
       l = l[0:-1]
       l = l.split()
       for a in l:
           if a in di.keys():
               di[a].append(count)
           else:
               di[a] = [count]
   for l in wlist:
       hat = 0
       if l in di.keys():
           print(l, end=\" \")
           for k in di[l]:
               if(hat>0):
                   print(\",\", end=\'\')
               print(k,end=\'\')
               hat = hat + 1
       print(\'\')
index(\'aven.txt\', [\'raven\', \'mortal\', \'dying\', \'ghost\',\'ghastly\', \'evil\',\'demon\'])
index(\'raven.txt\', [\'raven\', \'mortal\', \'dying\', \'ghost\',\'ghastly\', \'evil\',\'demon\'])

Could someone please provide the code for both of these problems in PYTHON 3 please? FIRST PART: At the end of this and other textbooks, there usually is an ind
Could someone please provide the code for both of these problems in PYTHON 3 please? FIRST PART: At the end of this and other textbooks, there usually is an ind

Get Help Now

Submit a Take Down Notice

Tutor
Tutor: Dr Jack
Most rated tutor on our site