Python: Finding the Most Frequent Word

By: fyvo July 27, 2025 Python

Description

This Python code analyzes text, counts word frequencies, and identifies the most frequent word. It handles punctuation and case-insensitivity for accurate results.

Code Snippet

import re
from collections import Counter

def most_frequent_word(text):
    """Finds the most frequent word in a given text."""
    text = text.lower()
    words = re.findall(r'\b\w+\b', text)  # Extract words, ignoring punctuation
    word_counts = Counter(words)
    most_frequent = word_counts.most_common(1)
    if most_frequent:
        return most_frequent[0][0]
    else:
        return None

text = "This is a sample text. This text is quite simple."
most_frequent = most_frequent_word(text)
print(f"The most frequent word is: {most_frequent}")

Discussion (0)