Count Characters, Words, and Lines in Python Text

Counts characters, words, lines, and the most common words in a given string using Python's standard library.

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

Python code

23 lines
Python 3.9+
from collections import Counter


def count_data(text):
    """Count characters, words, lines, and most common words in text."""
    char_count = len(text)
    word_count = len(text.split())
    line_count = text.count("\n") + 1
    word_freq = Counter(text.lower().split())
    most_common = word_freq.most_common(3)

    return {
        "characters": char_count,
        "words": word_count,
        "lines": line_count,
        "most_common_words": most_common,
    }


if __name__ == "__main__":
    sample_text = "The quick brown fox jumps over the lazy dog\nThe dog sleeps."
    result = count_data(sample_text)
    print(result)

Output

stdout
{'characters': 52, 'words': 10, 'lines': 2, 'most_common_words': [('the', 3), ('dog', 2), ('quick', 1)]}

How it works

The Counter from the collections module tallies word frequencies efficiently. text.split() splits on whitespace and counts words; text.count("\n") + 1 gives line count, assuming text ends without a newline. The function returns a dictionary with easy-to-read metrics. This pattern is useful for quick text analysis without external dependencies.

Common mistakes

  • Forgetting to lower-case text before counting most common words, causing case-sensitive duplicates.
  • Counting a trailing newline as an extra line when using `count("\n") + 1` without adjusting for empty lines.
  • Assuming `split()` splits on punctuation, but it only splits on whitespace.

Variations

  1. Use `re.findall(r'\b\w+\b', text.lower())` to count words with regex for better punctuation handling.
  2. Return a sorted list of all word frequencies instead of only the top 3.

Real-world use cases

  • Generating content statistics for a blog post editor to show word count and readability hints.
  • Analyzing log files to identify the most frequent error messages for troubleshooting.
  • Building a simple text summary tool that reports key metrics before further NLP processing.

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.