Program to count the frequency of words in the given argument using Python

by | Mar 12, 2021 | Python Programs

Home » Python » Python Programs » Program to count the frequency of words in the given argument using Python

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 to count the frequency of words in the given argument

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

Program to count the frequency of words in the given argument Ouput

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.

Author

0 Comments

Submit a Comment

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Author