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.

Easy Python 3.9+ Aug 9, 2026 Strings & text 14 views 0 copies

Python code

20 lines
Python 3.9+
def 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

stdout
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

  1. Use `re.findall(r'\w+', text)` to extract only alphanumeric words, ignoring punctuation.
  2. 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

Run this sample

Open the browser IDE to tweak the example and see results without installing anything.

Open editor

More from Strings & text

Related tutorials and quizzes for this topic.