Exercise 81

Develop a Python function that accepts a string, denoted as s, as its parameter. This function is designed to generate a dictionary where the keys represent the distinct words in the input string s, and the corresponding values indicate the frequency of each word within the given text.
For instance : consider the following example: if s = "I use Python for datascience but I don't use Python for mobile" the resulting dictionary would be:

{
    'I': 2,
    'use': 2,
    'Python': 2,
    'for': 2,
    'datascience': 1,
    'but': 1,
    "don't": 1,
    'mobile': 1
}

Solution

def word_occurrences(s):
    # Split the input string into a list of words
    words = s.split()

    # Initialize an empty dictionary to store word occurrences
    word_count = {}

    # Iterate through the list of words
    for word in words:
        # Remove punctuation marks (optional)
        word = word.strip(".,!?")

        # Convert the word to lowercase to make the count case-insensitive
        word = word.lower()

        # Update the dictionary with the word count
        word_count[word] = word_count.get(word, 0) + 1

    return word_count

# Example usage
s = "I use Python for datascience but I don't use Python for mobile"
result = word_occurrences(s)
print(result)
"""
output:
{'i': 2, 'use': 2, 'python': 2, 
 'for': 2, 'datascience': 1, 
 'but': 1, "don't": 1, 'mobile': 1}
"""




 

Younes Derfoufi
CRMEF OUJDA

One thought on “Solution Exercise 81 : Python Word Frequency Analysis in dictionary”

Leave a Reply