How can I print out the number of times each unique word appears in a inputted string?

Question:

How can I print out the number of times each unique word appeared in a inputted string? I already have the program to run so that it prints out the number of unique words that appear in the string. Although, I want to add it to it, so that it prints out the number of times each unique word appears in the inputted string.

Like:

The word ‘here’ appeared 6 times

The word ‘net’ appeared 7 times

the word ‘hello’ appeared 5 times

and so on

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)

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")
print("The word", words, "")
Asked By: Axel Palomino

||

Answers:

You seem to be aware of collections.Counter but never use it which is a shame because it does exactly what you need.

>>> from collections import Counter
>>> Counter("hello world foo bar hello".split())
Counter({'hello': 2, 'world': 1, 'foo': 1, 'bar': 1})
>>> for word, count in Counter("hello world foo bar hello".split()).items():
...   print(f"The word '{word}' appeared {count} time(s)")
... 
The word 'hello' appeared 2 time(s)
The word 'world' appeared 1 time(s)
The word 'foo' appeared 1 time(s)
The word 'bar' appeared 1 time(s)
Answered By: Chris
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.