Word & Character Counter — Developer Code Samples

Count words, characters, sentences, paragraphs, and estimate reading time programmatically. These patterns are useful for content validation, SEO meta-description length checking, and text analysis pipelines.

Try the interactive version online: Open Word & Character Counter Tool →

Parameters

Parameter Type Required Description
text str Yes Input text to analyze
reading_wpm int No Words per minute for reading time calculation (default: 200)

Returns: Dict with word_count, char_count, char_no_spaces, sentence_count, paragraph_count, reading_time_minutes, top_words

Code Examples

import re

def count_text(text):
    """Count words, characters, sentences, paragraphs, and reading time."""
    # Characters
    char_count = len(text)
    char_no_spaces = len(text.replace(' ', '').replace('\n', ''))

    # Words (split on whitespace)
    words = text.split()
    word_count = len(words)

    # Sentences (split on . ! ?)
    sentences = [s.strip() for s in re.split(r'[.!?]+', text) if s.strip()]
    sentence_count = len(sentences)

    # Paragraphs
    paragraphs = [p.strip() for p in text.split('\n\n') if p.strip()]
    paragraph_count = len(paragraphs)

    # Reading time (average 200 words per minute)
    reading_time_min = word_count / 200
    reading_time_sec = int(reading_time_min * 60)

    # Most frequent words (top 10, lowercase, filtered)
    stop_words = {'the', 'a', 'an', 'is', 'in', 'it', 'of', 'and', 'to', 'for'}
    word_freq = {}
    for w in words:
        w_clean = re.sub(r'[^a-z]', '', w.lower())
        if w_clean and w_clean not in stop_words:
            word_freq[w_clean] = word_freq.get(w_clean, 0) + 1
    top_words = sorted(word_freq.items(), key=lambda x: -x[1])[:10]

    return {
        "word_count": word_count,
        "char_count": char_count,
        "char_no_spaces": char_no_spaces,
        "sentence_count": sentence_count,
        "paragraph_count": paragraph_count,
        "reading_time_minutes": round(reading_time_min, 1),
        "reading_time_seconds": reading_time_sec,
        "avg_word_length": round(char_no_spaces / word_count, 1) if word_count else 0,
        "top_words": top_words,
    }

sample = "The quick brown fox jumps over the lazy dog. It is a short sentence."
result = count_text(sample)
print(result)