Table of Contents
Introduction
In this section of python programming, our task is to count the word frequency in the given statement. The word frequency basically means to count the occurrence of words. In dealing with complex domains of programming, we can often come into the scenario to count the word occurrence, this section will discuss the ways to solve the issue.
Program
from collections import Counter input_string = 'The joy of coding Python should be in seeing short, concise, readable statements' print("Input string is: "+input_string + "\n") output1 = {key:input_string.count(key) for key in input_string.split()} #Using dictionary comprehension print("Output using dictionary comprehension : "+str(output1)) #Using Count()+split() output2 = Counter(input_string.split()) print("Output using Counter() and split() : "+str(dict(output2)))
Output
Explanation
In the above python code, to achieve our task we have used two ways: 1. Using dictionary comprehension; 2. Using Counter() with split().
In the first method, we split all the words in the given argument and then performed count on them using count(). The output is displayed using print function.
Similar to the first method, we split the given argument and performed count on them. The only difference is we have used Counter() function to count frequency.
0 Comments