Python – Words Frequency in String Shorthands

Sometimes while working with Python strings, we can have problem in which we need to extract frequency of all the words in string. This problem has been solved earlier. This discusses the shorthands to solve this problem as this has application in many domains ranging from web development and competitive programming. Let’s discuss certain ways in which this problem can be solved.

Input : test_str = ‘Gfg is best’
Output : {‘Gfg’: 1, ‘is’: 1, ‘best’: 1}

Input : test_str = ‘Gfg Gfg Gfg’
Output : {‘Gfg’: 3}

Method #1 : Using dictionary comprehension + count() + split()
The combination of above functions can be used to solve this problem. In this, we first split all the words and then perform count of them using count().

filter_none

edit
close

play_arrow

link
brightness_4
code

# Python3 code to demonstrate working of 
# Words Frequency in String Shorthands
# Using dictionary comprehension + count() + split()
  
# initializing string
test_str = 'Gfg is best . Geeks are good and Geeks like Gfg'
  
# printing original string
print("The original string is : " + str(test_str))
  
# Words Frequency in String Shorthands
# Using dictionary comprehension + count() + split()
res = {key: test_str.count(key) for key in test_str.split()}
  
# printing result 
print("The words frequency : " + str(res)) 

chevron_right


Output :



The original string is : Gfg is best . Geeks are good and Geeks like Gfg
The words frequency : {‘Gfg’: 2, ‘is’: 1, ‘best’: 1, ‘.’: 1, ‘Geeks’: 2, ‘are’: 1, ‘good’: 1, ‘and’: 1, ‘like’: 1}

 

Method #2 : Using Counter() + split()
The combination of above methods can also be used to solve this problem. In this, we perform the task of counting using Counter() and separation of words using split().

filter_none

edit
close

play_arrow

link
brightness_4
code

# Python3 code to demonstrate working of 
# Words Frequency in String Shorthands
# Using Counter() + split()
from collections import Counter
  
# initializing string
test_str = 'Gfg is best . Geeks are good and Geeks like Gfg'
  
# printing original string
print("The original string is : " + str(test_str))
  
# Words Frequency in String Shorthands
# Using Counter() + split()
res = Counter(test_str.split())
  
# printing result 
print("The words frequency : " + str(dict(res))) 

chevron_right


Output :

The original string is : Gfg is best . Geeks are good and Geeks like Gfg
The words frequency : {‘Gfg’: 2, ‘is’: 1, ‘best’: 1, ‘.’: 1, ‘Geeks’: 2, ‘are’: 1, ‘good’: 1, ‘and’: 1, ‘like’: 1}




My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.