Text Analyzer
Completed
Read lines until END. Print: number of lines, number of words, the 3 most common words (lowercase, ignore punctuation, ties alphabetical) as word:count, and the average word length with 2 decimals.
Input
Lines of text, then END.
Output
Four lines.
Example
Input
The cat sat on the mat. The dog sat too! END
Output
2 10 the:3 sat:2 cat:1 2.90
Editor
Python
Hints
A regex is the easiest way to pull out words without punctuation.
Counter does the counting.
Solution explanation
This combines input loops, regular expressions, Counter, sorting and formatting.
Show solution
import re
from collections import Counter
lines = []
while (line := input()) != "END":
lines.append(line)
words = re.findall(r"[a-z']+", " ".join(lines).lower())
counts = Counter(words)
top = sorted(counts.items(), key=lambda kv: (-kv[1], kv[0]))[:3]
print(len(lines))
print(len(words))
print(*[f"{w}:{c}" for w, c in top])
print(f"{sum(map(len, words)) / len(words):.2f}")