LearnFrenzy
Sign in Take a free test

Strings · Strings Coding Problems · Question 10

Count words and unique words in a paragraph in Python Solution, output & explanation

  • Program
  • Medium
  • 0 comments
  • Answer explained
  • Moderated community
Question 10 Back to Exercise

Count the total words, the unique words (ignoring case and punctuation) and the most common word of a paragraph.

Solution
main.py Run
text = """Python is easy. Python is powerful.
Learning Python is fun, and fun is important!"""

words = [w.strip(".,!?").lower() for w in text.split()]
counts = {}
for w in words:
    counts[w] = counts.get(w, 0) + 1

top = max(counts, key=counts.get)
print("Total words:", len(words))
print("Unique words:", len(counts))
print("Most common:", top, counts[top])

Output Verified by running it on Python 3

Total words: 14
Unique words: 8
Most common: is 4

split() also splits across the newline. max(counts, key=counts.get) finds the key with the largest count; "is" (4) beats "python" (3).

Discussion & Comments 0

Share your method, a shortcut, or ask about a step you didn't follow.

No comments yet. Be the first to share your solution!

Post your comment

Comments appear after a quick review by our team.

Search LearnFrenzy

Esc

Quick links