Word Frequency Counter Function

  • Share this:

Code introduction


This function takes a text as input, splits it into words, counts the frequency of each word, and returns a Counter object containing the words and their frequencies.


Technology Stack : collections.Counter

Code Type : Python Function

Code Difficulty : Intermediate


                
                    
import random
from collections import Counter

def generate_word_frequency(text):
    # Tokenize the text into words
    words = text.split()
    # Count the frequency of each word
    word_count = Counter(words)
    return word_count

# Usage example
sample_text = "Hello world! This is a sample text. This text is used to demonstrate the word frequency function."
word_freq = generate_word_frequency(sample_text)

print(word_freq)