Find the best solutions to your problems with the help of IDNLearn.com. Our platform provides accurate, detailed responses to help you navigate any topic with ease.

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.

We value your presence here. Keep sharing knowledge and helping others find the answers they need. This community is the perfect place to learn together. Thank you for trusting IDNLearn.com with your questions. Visit us again for clear, concise, and accurate answers.