How to Build a Basic Text Processor in Python
Split text into sentences, count words, find the longest word, and convert text to uppercase — all with pure Python string methods.
Python code
21 linestext = """The quick brown fox jumps over the lazy dog.
Python is a powerful programming language.
Keep practicing every single day!"""
sentences = text.split(". ")
word_count = 0
longest_word = ""
for sentence in sentences:
words = sentence.split()
word_count += len(words)
for word in words:
cleaned = word.strip(".,!?")
if len(cleaned) > len(longest_word):
longest_word = cleaned
print(f"Original text:\n{text}")
print(f"\nNumber of sentences: {len(sentences)}")
print(f"Total word count: {word_count}")
print(f"Longest word: {longest_word}")
print(f"Text in uppercase: {text.upper()}")
Output
Original text:
The quick brown fox jumps over the lazy dog.
Python is a powerful programming language.
Keep practicing every single day!
Number of sentences: 3
Total word count: 18
Longest word: programming
Text in uppercase: THE QUICK BROWN FOX JUMPS OVER THE LAZY DOG.
PYTHON IS A POWERFUL PROGRAMMING LANGUAGE.
KEEP PRACTICING EVERY SINGLE DAY!
How it works
The code uses split() to break text into sentences by the . delimiter, then loops through each sentence to count words. The inner loop strips punctuation with strip(".,!?") and compares each cleaned word's length to track the longest one. Finally, f-strings format the output, and .upper() transforms the entire text to uppercase. This demonstrates foundational string manipulation that scales to real-world parsing tasks.
Common mistakes
- Assuming split('. ') handles sentences ending with '?' or '!' — it only splits on that exact delimiter
- Forgetting to strip punctuation before measuring word length, which inflates counts
- Not handling empty strings or single-sentence inputs gracefully
Variations
- Use `re.split(r'[.!?]\s+', text)` to split on multiple sentence-ending punctuation marks
- Use a list comprehension to extract words: `words = [word.strip('.,!?') for sentence in sentences for word in sentence.split()]`
Real-world use cases
- Analyzing customer feedback or survey responses to extract key metrics like sentence count and trending keywords.
- Building a simple search or index feature that tokenizes document text for keyword matching.
- Processing chat logs or transcripts to summarize conversation length and identify dominant topics.
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.