90.6k views
16 votes
Write a program that opens a specified text file then displays a list of all the unique words found in the file.

1 Answer

10 votes

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)

Step-by-step 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.

User Elmex
by
5.8k points