![]() |
VOOZH | about |
Given a string, the task is to find how many times each word appears in it. For example, the string "hello world hello everyone" should output each word with its frequency count.
Example:
Input: "hello world hello everyone"
Output: {'hello': 2, 'world': 1, 'everyone': 1}
Let’s explore different methods to find word frequency in Python.
Counter() automatically counts how many times each word appears in a list when you split the string into words using .split().
Counter({'hello': 2, 'world': 1, 'everyone': 1})
Explanation:
Using dict.get() with a for loop allows you to efficiently count occurrences of each character or word in a string. The get() method retrieves the current count and if the character or word isn't in the dictionary yet, it returns a default value (usually 0).
{'hello': 2, 'world': 1, 'everyone': 1}
Explanation:
This is another efficient dictionary-based approach where every missing key is automatically initialized to 0.
{'hello': 2, 'world': 1, 'everyone': 1}
Explanation:
Using list comprehension with collections.Counter allows you to efficiently count the frequency of elements by transforming the data (such as characters or words in a string) and applying Counter to generate frequency counts.
Counter({'hello': 2, 'world': 1, 'everyone': 1})
Explanation: