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.
Python code
32 linesdef 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
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
- Use regular expressions to count sentences more accurately with `re.split(r'(?<=[.!?])\s+', text)`.
- 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
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.