Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

Python program t4.py file apple 1 1 ball art dog & pen rat 4 apple 1@. carrot !

ID: 3919639 • Letter: P

Question

Python program

t4.py file

apple

1

1

ball

art

dog

&

pen

rat

4

apple

1@.

carrot

!

orange

ant

ant

ant

ball

stick

pen

_

$a

***

goodbye

The Program Spec Write a program that reads in a filename provided by the user, opens it and reads all of the lines. Create a dictionary to hold the line numbers for each valid identifier found. Your solution will need to process each ine to determine whether a valid identifier exists on that line and if so,record both the line number and identifier found in the dictionary A valid identifier must be a string consisting of only letters, numbers and underscores. If a line contains an invalid identifier no record is made in the dictionary. If a line contains a valid identifier already recorded in the dictionary append the line number to the dictionary log of where the identifier was found Input Error Checking: For simplicity a python file is provided to feed into your dictionary generator. filename is t4.py provided in the link below Test Run Requirements: Use the provided t4.py file as your test run validator. Here are some other tips and requirements 1. Keep provided test file intact 2. Use t4.py as your input test file to generate submission run output 3. Verify identifiers are valid; ignore if invalid Here is a sample run: The apple: (1, 11 art:[5

Explanation / Answer

CODING:

# reading file and taking lines

fname = input("Enter a file name:")

flines = open(fname, "r").read().split(" ")

d = {}

# looping through each line

for i in range(len(flines)):

word = flines[i]

flag = True

# this is to check if word has valid characters

for letter in word:

if not((letter>='a' and letter <='z') or (letter>='A' and letter<='Z') or letter == '_'):

flag = False

break

# if no invalid characters are there

if flag:

if word in d:

d[word].append(i+1)

else:

d[word] = [i+1]

# printing output

for each in d:

print(each, d[each])

SAMPLE OUTPUT:

Enter a file name: t4.py

apple [1, 11]

ball [4, 19]

art [5]

dog [6]

pen [8, 21]

rat [9]

carrot [13]

orange [15]

ant [16, 17, 18]

stick [20]

_ [22]

goodbye [25]

'''