Word Frequency in Sentence

Given a sentence as a string, write a Python program to count the occurrences of each word in the sentence.

Example 1:

Input: "the quick brown fox jumps over the lazy dog" 
Output: {'the': 2, 'quick': 1, 'brown': 1, 'fox': 1, 'jumps': 1, 'over': 1, 'lazy': 1, 'dog': 1}

Example 2:

Input: "apple banana apple strawberry banana lemon" 
Output: {'apple': 2, 'banana': 2, 'strawberry': 1, 'lemon': 1}

Consider splitting the sentence into words, then use a dictionary to count the occurrences of each word.

def word_frequency(sentence):
    words = sentence.split()
    frequency = {}
    for word in words:
        if word not in frequency:
            frequency[word] = 1
            frequency[word] += 1
    return frequency

© Let’s Data Science


Unlock AI & Data Science treasures. Log in!