Writing a program in Python that reads a text file and organizes the words in the file into a list without repeating words and in all lowercase.
Here is what I have
#This program takes a user input file name and returns each word
in a list
#and how many different words are in the program.
while True: #While loop to loop program
words = 0
#list1 =
['Programmers','add','an','operating','system','and','set','of','applications','to','the','hardware',
#
'we','end','up','with','a','Personal','Digital','Assistant','that','is','quite','helpful','capable',
#'helping','us','do','many','different','things']
try:
fname = input('Please
enter the file name to open:')
fhand =
open(fname)
list1 = list()
for line in fhand:
#Iteration over each line
words = line.split()
list1.append(words)
#words = [words.lower() for words in list1]
print('list',list1)
print('words',words)
sorted_list =
sorted(words)
print(sorted_list)
print('File',fname,'has',len(list1),'different words.')
ans = input("Do you want
try again? y/n: ") #asking user to contiune
if ans == 'y' or ans ==
'Y':
continue
else:
if ans == 'n' or ans == 'N':
print('Goodbye')
break
except:
print('File cannot be
opened:', fname)
continue
Program Code Screenshot :
Sample Output :
Program Code to Copy (Please refer to the screenshot of the code to understand the indentation of the code)
while True: #While loop to loop program
try:
#Open a file
fname = input('Please enter the file name to open: ')
fhand = open(fname)
#List to store all the words
list1 = []
#Open all lines in the file
for line in fhand: #Iteration over each line
words = line.split()
#Add to list
list1.extend([word.lower() for word in words])
print('list',list1)
#Print count of different words
print('File',fname,'has',len(set(list1)),'different words.')
#Prompt again
ans = input("Do you want try again? y/n: ") #asking user to
contiune
if ans == 'y' or ans == 'Y':
continue
else:
if ans == 'n' or ans == 'N':
print('Goodbye')
break
except:
print('File cannot be opened:', fname)
continue
Get Answers For Free
Most questions answered within 1 hours.