Computer >> Computer tutorials >  >> Programming >> Python

Python – Word Frequency in a String


When it is required to find the frequency of words using the string shorthand, dictionary comprehension can be used.

Example

Below is a demonstration of the same

my_str = 'Hi there Will, how are you Will, Will you say Hi to me'
print("The string is : " )
print(my_str)
my_result = {key: my_str.count(key) for key in my_str.split()}
print("The word frequency is : ")
print(my_result)

Output

The string is :
Hi there Will, how are you Will, Will you say Hi to me
The word frequency is :
{'Hi': 2, 'there': 1, 'Will,': 2, 'how': 1, 'are': 1, 'you': 2, 'Will': 3, 'say': 1, 'to': 1, 'me': 1}

Explanation

  • A string is defined, and is displayed on the console.

  • The dictionary comprehension is used to iterate through the string, and split it based on spaces.

  • The count of ‘key’ is determined, and is assigned to a variable.

  • This variable is displayed as output on the console.