Get detailed and accurate answers to your questions on IDNLearn.com. Our platform provides trustworthy answers to help you make informed decisions quickly and easily.

Write a program that opens a specified text file then displays a list of all the unique words found in the file.

Sagot :

Answer:

filename = input("Enter file name with extension:")

words = []

with open(filename, "r") as file:

   # read the file line by line, with each line an item in the returned list

   line_list = file.readlines()

   # loop through the list to get the words from the strings

   for line in line_list:

       word_list = line.split(" ")

       for i in word_list:

           words.append(i)

# use the set() to get the unique items of the list as a set

# and convert it back to a list, then display the list.

su_words = set(words)

unique_words = list(su_words)

print(unique_words)

Explanation:

The python program gets the file name from the user input method. The with keyword is used to open and read the file which is read line by line as a list of strings (each line is a string). The for loop is used to append each word to the words list and the set() function cast the words list to a set of unique words. The set is in turn converted back to a list and displayed.