Open In App

Python – Words Frequency in String Shorthands

Last Updated : 10 May, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

Sometimes while working with Python strings, we can have a problem in which we need to extract the frequency of all the words in a string. This problem has been solved earlier. This discusses the shorthands to solve this problem as this has applications 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 the above functions can be used to solve this problem. In this, we first split all the words and then perform a count of them using count() method.

Python3




# 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))


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}

Time Complexity: O(n)
Auxiliary Space: O(n)

Method #2: Using Counter() + split() 

The combination of the 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(). 

Python3




# 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)))


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 #3 : Using dictionary comprehension + operator.countOf() + split() :

The combination of the above functions can be used to solve this problem. In this, we first split all the words and then perform count of them using operator.countOf() method.

Python3




# Python3 code to demonstrate working of
# Words Frequency in String Shorthands
# Using dictionary comprehension + operator.countOf() + split()
 
import operator as op
 
# 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))
listString = test_str.split()
 
# Words Frequency in String Shorthands
# Using dictionary comprehension + operator.countOf()
res = {key: op.countOf(listString, key) for key in listString}
 
# Printing the result
print("The words frequency : " + str(res))


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}

Time Complexity: O(N)
Auxiliary Space : O(N)

Method #4: Using defaultdict

Python3




from collections import defaultdict
 
# 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))
 
# Split the string into a list of words
listString = test_str.split()
 
# Creating a defaultdict with default value 0
freq = defaultdict(int)
 
# Iterating through the list of words and
# count the frequency of each word
for word in listString:
    freq[word] += 1
 
# Converting the defaultdict to a regular dictionary
res = dict(freq)
 
# Printing result
print("The words frequency : " + str(res))


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}

Time Complexity: O(n), where n is the number of words in the string.
Auxiliary Space: O(n), where n is the number of unique words in the string.

Method #5: Using set() and list comprehension

Step-by-step approach:

  • Split the string into a list of words.
  • Use set() to get a unique set of words.
  • Use a list comprehension to count the frequency of each word in the original list.
  • Store the results in a dictionary using dictionary comprehension.
  • Print the final result.

Python3




# 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))
 
# Split the string into a list of words
listString = test_str.split()
 
# Using set() and list comprehension to count the frequency of each word
freq = {word: listString.count(word) for word in set(listString)}
 
# Printing result
print("The words frequency : " + str(freq))


Output

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

Time complexity: O(n^2) where n is the length of the list of words.
Auxiliary space: O(n) where n is the length of the list of words.



Previous Article
Next Article

Similar Reads

Python - Compute the frequency of words after removing stop words and stemming
In this article we are going to tokenize sentence, paragraph, and webpage contents using the NLTK toolkit in the python environment then we will remove stop words and apply stemming on the contents of sentences, paragraphs, and webpage. Finally, we will Compute the frequency of words after removing stop words and stemming. Modules Needed bs4: Beaut
8 min read
Python - List Words Frequency in String
Given a List of Words, Map frequency of each to occurrence in String. Input : test_str = 'geeksforgeeks is best for geeks and best for CS', count_list = ['best', 'geeksforgeeks', 'computer'] Output : [2, 1, 0] Explanation : best has 2 occ., geeksforgeeks 1 and computer is not present in string.Input : test_str = 'geeksforgeeks is best for geeks and
4 min read
Maximum length prefix such that frequency of each character is atmost number of characters with minimum frequency
Given a string S, the task is to find the prefix of string S with the maximum possible length such that frequency of each character in the prefix is at most the number of characters in S with minimum frequency. Examples: Input: S = 'aabcdaab' Output: aabcd Explanation: Frequency of characters in the given string - {a: 4, b: 2, c: 1, d: 1} Minimum f
8 min read
Reverse Words in a Given String in Python
We are given a string and we need to reverse words of a given string Examples: Input : str =" geeks quiz practice code" Output : str = code practice quiz geeks Input : str = "my name is laxmi" output : str= laxmi is name my Reverse the words in the given string program C/C++ Code # Python code # To reverse words in a given string # input string str
6 min read
Python | Extract words from given string
In Python, we sometimes come through situations where we require to get all the words present in the string, this can be a tedious task done using the native method. Hence having shorthand to perform this task is always useful. Additionally, this article also includes the cases in which punctuation marks have to be ignored. Input: GeeksForGeeks is
5 min read
Iterate over words of a String in Python
Given a String comprising of many words separated by space, write a Python program to iterate over these words of the string. Examples: Input: str = "GeeksforGeeks is a computer science portal for Geeks" Output: GeeksforGeeks is a computer science portal for Geeks Input: str = "Geeks for Geeks" Output: Geeks for Geeks Method 1: Using split() Using
4 min read
Python | Words lengths in String
We sometimes come through situations where we require to get all the word lengths present in the string, this can be a tedious task done using a naive method. Hence having shorthand to perform this task is always useful. Let's discuss certain ways to achieve this. Method #1 : Using split() + len() Using the split function, we can split the string i
5 min read
Python | Extract odd length words in String
Sometimes, while working with Python, we can have a problem in which we need to extract certain length words from a string. This can be extraction of odd length words from the string. This can have application in many domains including day-day programming. Lets discuss certain ways in which this task can be performed. Method #1 : Using loop This is
5 min read
Python - Eliminate Capital Letter Starting words from String
Sometimes, while working with Python Strings, we can have a problem in which we need to remove all the words beginning with capital letters. Words that begin with capital letters are proper nouns and their occurrence mean different meaning to the sentence and can be sometimes undesired. Let's discuss certain ways in which this task can be performed
7 min read
Python - Extract words starting with K in String List
Given list of phrases, extract all the Strings with begin with character K. Input : test_list = ["Gfg is good for learning", "Gfg is for geeks", "I love G4G"], K = l Output : ['learning', 'love'] Explanation : All elements with L as starting letter are extracted. Input : test_list = ["Gfg is good for learning", "Gfg is for geeks", "I love G4G"], K
7 min read
Practice Tags :
three90RightbarBannerImg