Brain teasers: Counting word frequency

Counting word frequency is a common programming task where we analyze a text document or string to determine how frequently each word appears within it. This exercise is useful for various applications, such as text analysis, natural language processing, and creating word clouds.

Brain teasers: Counting word frequency

The problem statement:

Given a string find the frequency of each word in that string.

Counting word frequency is a common programming task where we analyze a text document or string to determine how frequently each word appears within it. This exercise is useful for various applications, such as text analysis, natural language processing, and creating word clouds.

Here is a sample text for analysis along with the defined word_frequency() function.

nursery_rhyme: str = f'The itsy bitsy spider crawled up the water spout. ' \
                     f'Down came the rain, and washed the spider out. ' \
                     f'Out came the sun, and dried up all the rain, ' \
                     f'and the itsy bitsy spider went up the spout again.'

def word_frequency(text: str) -> dict[str, int]:
    ...

The above code can be used as a starting point to solve the problem. The possible output could look as follows.

{
    ...,
    'itsy': 2, 
    'rain': 2, 
    'the': 8, 
    'up': 3,
    ...
}
💡
EXTRA TASK: Given a string find the most common word in that string.

If you need to refresh your knowledge, follow the link below. 👇👇👇

Exploring Python
Python is frequently utilized in creating websites and software, as well as for automating tasks, analyzing data, and visualizing information.

Solution

Looking at the provided code we can easily notice that our function has to take the text to process and return a dictionary with word-to-counter mappings.