SHARE
SPREAD
HELP

The Tradition of Sharing

Help your friends and juniors by posting answers to the questions that you know. Also post questions that are not available.


To start with, Sr2Jr’s first step is to reduce the expenses related to education. To achieve this goal Sr2Jr organized the textbook’s question and answers. Sr2Jr is community based and need your support to fill the question and answers. The question and answers posted will be available free of cost to all.

 

#
Authors:
Tony Gaddis
Chapter:
Dictionaries And Sets
Exercise:
Programming Exercises
Question:4 | ISBN:9780132576376 | Edition: 2

Question

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.

TextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbook

Answer

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

 

0 0

Discussions

Post the discussion to improve the above solution.