How to Summarize Text Statistics in Python
This function returns basic statistics about a string, including character, word, and sentence counts, plus case and digit counts.
Python code
20 linesdef summarize_text(text):
"""Return basic statistics about a string."""
words = text.split()
return {
"characters": len(text),
"words": len(words),
"sentences": text.count(".") + text.count("!") + text.count("?"),
"uppercase": sum(c.isupper() for c in text),
"lowercase": sum(c.islower() for c in text),
"digits": sum(c.isdigit() for c in text),
"first_word": words[0] if words else "",
"last_word": words[-1] if words else "",
}
if __name__ == "__main__":
sample = "Hello, Python learners! Practice makes perfect."
stats = summarize_text(sample)
for key, value in stats.items():
print(f"{key}: {value}")
Output
characters: 42
words: 6
sentences: 2
uppercase: 2
lowercase: 35
digits: 0
first_word: Hello,
last_word: perfect.
How it works
The split() method divides the string on whitespace, which provides a straightforward word count. Counting terminal punctuation (., !, ?) approximates sentence boundaries, which works for simple text. Using generators like sum(c.isupper() for c in text) counts characters without extra loops. The function handles empty strings gracefully via if words else ''. This approach is efficient for strings of moderate size and uses only the Python standard library.
Common mistakes
- Counting sentences by punctuation only can mislead with abbreviations or decimal points.
- Assuming `text.split()` splits on any whitespace — it does, but multiple spaces are ignored, which is usually fine.
- Forgetting to handle empty strings, which would cause an IndexError when accessing `words[0]`.
Variations
- Use `re.findall(r'\w+', text)` to extract only alphanumeric words, ignoring punctuation.
- Compute readability scores (e.g., Flesch) using more advanced text analysis libraries.
Real-world use cases
- Quickly assess the length and complexity of user-generated content before sending to a summarizer.
- Track basic content metrics in a CMS to flag very short or overly long posts.
- Provide instant word/character counts in a text editor or writing app.
Sponsored
More from Strings & text
- Automatically Detect Weak Passwords from Large Password Lists in Python easy
- Build CSV row from Python list with proper quoting easy
- Build a Secure Password Strength Checker in Python easy
- Convert Natural Language Dates to Datetime in Python medium
- Count Characters, Words, and Lines in Python Text easy
- Extract Data from Strings in Python: Beginner's Guide easy
Keep learning
Related tutorials and quizzes for this topic.