Random Word Frequency Counter

  • Share this:

Code introduction


This function takes a sentence as input, counts the occurrences of each word in the sentence, and returns the most common word and its count.


Technology Stack : collections.Counter

Code Type : Function

Code Difficulty : Intermediate


                
                    
import random
from collections import Counter

def random_word_count(sentence):
    # Split the sentence into words
    words = sentence.split()
    # Count the occurrences of each word
    word_counts = Counter(words)
    # Return the most common word and its count
    return word_counts.most_common(1)[0]

# Code Information