Unique Words
Write a program that opens a specified text file and then displays a list of all the unique words found in the file.
Hint: Store each word as an element of a set.
Unique Words program code:
def getUniqueWords(inputFilePath):
uniqueWords = set()
with open(inputFilePath, 'r') as file:
# Read the contents of the file
contents = file.read()
# Split the contents into individual words
words = contents.split()
# Iterate through each word
for word in words:
# Remove any leading or trailing punctuation from the word
word = word.strip(".,!?;:\"'()[]{}")
# Add the word to the set of unique words
uniqueWords.add(word)
return uniqueWords
# Usage example
inputFilePath = "input.txt" # Replace with the path to your text file
uniqueWords = getUniqueWords(inputFilePath)
# Display the unique words in the input file
print("Unique words in the input.txt file:")
for word in uniqueWords:
print(word)
Input file "input.txt" data:
Hello
Python
Hello
Java
Hello
World
Hello
Jhon
Good Charless
Good Mohamad
Executed Output:
Unique words in the input.txt file:
World
Jhon
Charless
Good
Python
Mohamad
Java
Hello