Looking for reliable answers? Westonci.ca is the ultimate Q&A platform where experts share their knowledge on various topics. Discover detailed answers to your questions from a wide network of experts on our comprehensive Q&A platform. Join our Q&A platform to connect with experts dedicated to providing accurate answers to your questions in various fields.

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.