How to build a text helper in Python for beginners

This code provides easy-to-use functions for cleaning text, removing punctuation, counting word frequencies, and summarizing strings — perfect for beginners.

Easy Python 3.10+ Aug 9, 2026 Strings & text 12 views 0 copies

Python code

40 lines
Python 3.10+
def clean_text(text: str) -> str:
    """Clean and normalize a text string."""
    text = text.strip()
    text = text.replace("  ", " ")
    text = text.capitalize()
    text = text.replace(".", ".")
    return text


def remove_punctuation(text: str) -> str:
    """Remove common punctuation marks from a string."""
    import string
    return ''.join(char for char in text if char not in string.punctuation)


def word_count(text: str) -> dict:
    """Count word frequencies in a text string."""
    words = text.lower().split()
    counts = {}
    for word in words:
        counts[word] = counts.get(word, 0) + 1
    return counts


def summarize(text: str, max_words: int = 10) -> str:
    """Create a brief summary of a text string."""
    words = text.split()
    if len(words) <= max_words:
        return text
    return ' '.join(words[:max_words]) + "..."



if __name__ == "__main__":
    sample = "  Python is a great language. python is fun!!   "
    print("Original:", repr(sample))
    print("Cleaned:", clean_text(sample))
    print("No punctuation:", remove_punctuation(sample))
    print("Word counts:", word_count(sample))
    print("Summary:", summarize(sample, max_words=5))

Output

stdout
Original: '  Python is a great language. python is fun!!   '
Cleaned: 'Python is a great language. python is fun!!'
No punctuation: 'Python is a great language python is fun'
Word counts: {'python': 2, 'is': 2, 'a': 1, 'great': 1, 'language': 1, 'fun': 1}
Summary: 'Python is a great...'

How it works

The clean_text function strips surrounding whitespace and collapses double spaces, then capitalizes only the first letter of the entire string. remove_punctuation uses the string module to filter out any character that is considered punctuation. word_count converts the text to lowercase, splits it into words, and builds a dictionary with counts using dict.get with a default of zero. summarize simply takes the first max_words words and appends an ellipsis if the text is longer. These functions are modular and can be reused independently.

Common mistakes

  • Assuming `clean_text` removes all extra spaces, but it only replaces double spaces, not tabs or multiple spaces with more than two.
  • Forgetting that `remove_punctuation` also removes apostrophes inside words like "don't".
  • Using `str.split()` without lowercasing, leading to inconsistent word counts for words like 'Python' and 'python'.
  • Not handling empty strings in `word_count`, which would raise an IndexError or return an empty dict without issues.

Variations

  1. Use a list comprehension with `str.isalnum()` to remove punctuation while keeping spaces.
  2. Use `collections.Counter` to count word frequencies more concisely.

Real-world use cases

  • Cleaning user-generated comments before analyzing sentiment in a social media dashboard.
  • Tokenizing and counting words in customer reviews to generate tag clouds.
  • Creating short previews for blog posts or news articles by truncating text to a fixed 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.