Answer to Question #315352 in Python for Michael

Question #315352

Sanjay identifies that for compiler designing he need to implement tokenization of a specific line of program. As a friend of Sanjay, your task is to help him to write a python function Tokenize_Line(fname, n) which reads nth line from prime.py file and returns a list containing all tokens of that line as shown in the example. Also, handle the possible exception and provide proper message.

 

Contents of prime.py file will be like:

from math import sqrt

n = 1

prime_flag = 0

if(n > 1):

   for i in range(2, int(sqrt(n)) + 1):

       if (n % i == 0):

prime_flag = 1

           break

   if (prime_flag == 0):

       print("true")

   else:

       print("false")

else:

   print("false")


Input:

prime.py

10

 Output:

['print("true")

']Input:

prime1.py

8

Output:

File Doesn't Exist


Input:

prime.py

6

Output:

['if', '(n', '%', 'i', '==', '0):']


Input:

prime.py

100

Output:

Invalid Line no.


1
Expert's answer
2022-03-21T16:10:13-0400
def Tokenize_Line(fname, n):
    try:
        file = open (fname, 'r')
        try:
            if n > sum(1 for line in file):
                return "Invalid Line no."
            else:
                file.seek(0)
                for i in range(n-1):
                    file.readline()                 
                rez = file.readline().split()
                return rez
        finally:
            file.close()
    except FileNotFoundError:
        return "File Doesn't Exist"
    
print('Enter filename: ', end='')
filename = input()
print('Enter line (n): ', end='')
n = int(input())
print(Tokenize_Line(filename, n))

Need a fast expert's response?

Submit order

and get a quick answer at the best price

for any assignment or question with DETAILED EXPLANATIONS!

Comments

No comments. Be the first!

Leave a comment

LATEST TUTORIALS
New on Blog
APPROVED BY CLIENTS