How do I print out the unique words of an inputted string?

Question:

I’m struggling to print out the unique words of the phrase a user inputs. The function get_count_of_unique_words() doesn’t seem to work. When a user inputs their chosen phrase or words, it needs to print out any unique or repeated words in that phrase.

from collections import Counter

user_text = input("Please enter some text --> ")


def word_count(user_text):
    return(len(user_text.strip().split(" ")))


number_of_characters = len(user_text)


def get_count_of_unique_words(user_text):
    selected_words = []
    for word in user_text:
        if word.isalpha():
           selected_words.append(word)

    unique_count = 0
    for letter, count in Counter(selected_words).items():
        if count == 1:
            unique_count += 1


print("You typed", number_of_characters, "characters")
print("You typed", word_count(user_text), "words")
print("There are", get_count_of_unique_words(user_text),"unique words")
Asked By: Axel Palomino

||

Answers:

Instead of passing user_text to the function, try creating a list of words that can be reused for both the word count and the unique words. Then, just get the unique elements in that list by converting it to a set and getting the length of the set. Like this:

user_text = input("Please enter some text --> ")

words = user_text.strip().split(' ')

print("You typed", len(user_text), "characters")
print("You typed", len(words), "words")
print("There are", len(set(words)), "unique words")

You could extract each of these statements into their own function, although you don’t need to. I chose not to because it makes the code a bit cleaner and shorter.

Answered By: Michael M.
Categories: questions Tags:
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.