How to Build a Text Processor in Python

This code defines functions to count words, sentences, and find the longest word in a text, then prints basic statistics like uppercase and lowercase versions.

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

Python code

32 lines
Python 3.9+
def count_words(text):
    return len(text.split())


def count_sentences(text):
    sentence_endings = ".!?"
    count = 0
    for char in text:
        if char in sentence_endings:
            count += 1
    return count


def longest_word(text):
    words = text.split()
    if not words:
        return ""
    return max(words, key=len)


def process_text(text):
    print(f"Original text: {text}")
    print(f"Word count: {count_words(text)}")
    print(f"Sentence count: {count_sentences(text)}")
    print(f"Longest word: {longest_word(text)}")
    print(f"Uppercase: {text.upper()}")
    print(f"Lowercase: {text.lower()}")


if __name__ == "__main__":
    sample = "Hello world! This is Python. It is fun."
    process_text(sample)

Output

stdout
Original text: Hello world! This is Python. It is fun.
Word count: 7
Sentence count: 3
Longest word: Python
Uppercase: HELLO WORLD! THIS IS PYTHON. IT IS FUN.
Lowercase: hello world! this is python. it is fun.

How it works

The count_words function uses split() which splits on whitespace, so it correctly counts words separated by spaces. count_sentences counts characters that are ., !, or ?; this works for simple cases but assumes sentences end with these punctuation marks. longest_word finds the maximum word based on length using max(key=len). The process_text function prints formatted output, making it easy to see text analysis at a glance.

Common mistakes

  • Not handling empty text for longest_word, but here it returns an empty string.
  • Counting decimal points as sentence endings, e.g., in '3.14'.
  • Assuming each sentence ends with punctuation; missing periods in abbreviations like 'Mr.'.
  • Using split(',') instead of split() when trying to count words.

Variations

  1. Use regular expressions to count sentences more accurately with `re.split(r'(?<=[.!?])\s+', text)`.
  2. Use `collections.Counter` to get word frequency along with counts.

Real-world use cases

  • Building a readability analyzer that computes word counts for content marketing reports.
  • Creating a simple text metrics tool to gauge essay length in educational apps.
  • Preprocessing user input in search features to extract keywords by length.

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.