Find frequency of each word in a string in Python
Last Updated :
20 Feb, 2023
Write a python code to find the frequency of each word in a given string. Examples:
Input : str[] = "Apple Mango Orange Mango Guava Guava Mango"
Output : frequency of Apple is : 1
frequency of Mango is : 3
frequency of Orange is : 1
frequency of Guava is : 2
Input : str = "Train Bus Bus Train Taxi Aeroplane Taxi Bus"
Output : frequency of Train is : 2
frequency of Bus is : 3
frequency of Taxi is : 2
frequency of Aeroplane is : 1
Approach 1 using list():
1. Split the string into a list containing the words by using split function (i.e. string.split()) in python with delimiter space.
Note:
string_name.split(separator) method is used to split the string
by specified separator(delimiter) into the list.
If delimiter is not provided then white space is a separator.
For example:
CODE : str='This is my book'
str.split()
OUTPUT : ['This', 'is', 'my', 'book']
2. Initialize a new empty list.
3. Now append the word to the new list from previous string if that word is not present in the new list.
4. Iterate over the new list and use count function (i.e. string.
Python3
def count(elements):
if elements[ - 1 ] = = '.' :
elements = elements[ 0 : len (elements) - 1 ]
if elements in dictionary:
dictionary[elements] + = 1
else :
dictionary.update({elements: 1 })
Sentence = "Apple Mango Orange Mango Guava Guava Mango"
dictionary = {}
lst = Sentence.split()
for elements in lst:
count(elements)
for allKeys in dictionary:
print ( "Frequency of " , allKeys, end = " " )
print ( ":" , end = " " )
print (dictionary[allKeys], end = " " )
print ()
|
Output
Frequency of Apple : 1
Frequency of Mango : 3
Frequency of Orange : 1
Frequency of Guava : 2
Time complexity : O(n)
Space complexity : O(n)
(newstring[iteration])) to find the frequency of word at each iteration.
Note:
string_name.count(substring) is used to find no. of occurrence of
substring in a given string.
For example:
CODE : str='Apple Mango Apple'
str.count('Apple')
str2='Apple'
str.count(str2)
OUTPUT : 2
2
Implementation:
Python3
def freq( str ):
str = str .split()
str2 = []
for i in str :
if i not in str2:
str2.append(i)
for i in range ( 0 , len (str2)):
print ( 'Frequency of' , str2[i], 'is :' , str .count(str2[i]))
def main():
str = 'apple mango apple orange orange apple guava mango mango'
freq( str )
if __name__ = = "__main__" :
main()
|
Output
Frequency of apple is : 3
Frequency of mango is : 3
Frequency of orange is : 2
Frequency of guava is : 1
Time complexity : O(n^2)
Space complexity : O(n)
Approach 2 using set():
- Split the string into a list containing the words by using split function (i.e. string.split()) in python with delimiter space.
- Use set() method to remove a duplicate and to give a set of unique words
- Iterate over the set and use count function (i.e. string.count(newstring[iteration])) to find the frequency of word at each iteration.
Implementation:
Python3
def freq( str ):
str_list = str .split()
unique_words = set (str_list)
for words in unique_words :
print ( 'Frequency of ' , words , 'is :' , str_list.count(words))
if __name__ = = "__main__" :
str = 'apple mango apple orange orange apple guava mango mango'
freq( str )
|
Output
Frequency of orange is : 2
Frequency of mango is : 3
Frequency of guava is : 1
Frequency of apple is : 3
Time complexity : O(n^2)
Space complexity : O(n)
Approach 3 (Using Dictionary):
Python3
def count(elements):
if elements[ - 1 ] = = '.' :
elements = elements[ 0 : len (elements) - 1 ]
if elements in dictionary:
dictionary[elements] + = 1
else :
dictionary.update({elements: 1 })
Sentence = "Apple Mango Orange Mango Guava Guava Mango"
dictionary = {}
lst = Sentence.split()
for elements in lst:
count(elements)
for allKeys in dictionary:
print ( "Frequency of " , allKeys, end = " " )
print ( ":" , end = " " )
print (dictionary[allKeys], end = " " )
print ()
|
Output
Frequency of Apple : 1
Frequency of Mango : 3
Frequency of Orange : 1
Frequency of Guava : 2
time complexity : O(m * n)
space complexity : O(k)
Approach 4: Using Counter() function:
Python3
from collections import Counter
def freq( str ):
str_list = str .split()
frequency = Counter(str_list)
for word in frequency:
print ( 'Frequency of ' , word, 'is :' , frequency[word])
if __name__ = = "__main__" :
str = 'apple mango apple orange orange apple guava mango mango'
freq( str )
|
Output
Frequency of apple is : 3
Frequency of mango is : 3
Frequency of orange is : 2
Frequency of guava is : 1
Time Complexity: O(n)
Auxiliary Space: O(n)
Approach 4 (Using setdefault):
Python3
def freq( str ):
str_list = str .split()
frequency = {}
for word in str_list:
frequency[word] = frequency.setdefault(word, 0 ) + 1
for key, value in frequency.items():
print (key, ':' , value)
str = 'apple mango apple orange orange apple guava mango mango'
freq( str )
|
Output
apple : 3
mango : 3
orange : 2
guava : 1
Time Complexity: O(n), where n is the length of the given string
Auxiliary Space: O(n)
Approach 5 :Using operator.countOf() method:
Python3
import operator as op
def freq( str ):
str = str .split()
str2 = []
for i in str :
if i not in str2:
str2.append(i)
for i in range ( 0 , len (str2)):
print ( 'Frequency of' , str2[i], 'is :' , op.countOf( str ,str2[i]))
def main():
str = 'apple mango apple orange orange apple guava mango mango'
freq( str )
if __name__ = = "__main__" :
main()
|
Output
Frequency of apple is : 3
Frequency of mango is : 3
Frequency of orange is : 2
Frequency of guava is : 1
Time Complexity: O(N), where n is the length of the given string
Auxiliary Space: O(N)
Similar Reads
Reverse Words in a Given String in Python
In this article, we explore various ways to reverse the words in a string using Python. From simple built-in methods to advanced techniques like recursion and stacks. We are going to see various techniques to reverse a string. Using split() and join()Using split() and join() is the most common metho
2 min read
Python - Count all prefixes in given string with greatest frequency
Counting all prefixes in a given string with the greatest frequency involves identifying substrings that start from the beginning of the string and determining which appears most frequently. Using a Dictionary (DefaultDict)This approach uses defaultdict from the collections module to store prefix co
3 min read
Python Capitalize First Letter of Every Word in String
There are different ways to capitalize the first letter of every word in a string using Python. We will cover methods such as using str.capitalize(), loops and regular expressions to achieve this text formatting task. Using str.title()str.title() method in Python converts the first character of each
3 min read
Python - Find all close matches of input string from a list
In Python, there are multiple ways to find all close matches of a given input string from a list of strings. Using startswith() startswith() function is used to identify close matches for the input string. It checks if either the strings in the list start with the input or if the input starts with t
3 min read
How to check if a string is a valid keyword in Python?
In programming, a keyword is a "reserved word" by the language that conveys special meaning to the interpreter. It may be a command or a parameter. Keywords cannot be used as a variable name in the program snippet. What is Keywords in PythonPython also reserves some keywords that convey special mean
2 min read
Find the first repeated word in a string in Python using Dictionary
We are given a string that may contain repeated words and the task is to find the first word that appears more than once. For example, in the string "Learn code learn fast", the word "learn" is the first repeated word. Let's understand different approaches to solve this problem using a dictionary. U
3 min read
How to Change Values in a String in Python
The task of changing values in a string in Python involves modifying specific parts of the string based on certain conditions. Since strings in Python are immutable, any modification requires creating a new string with the desired changes. For example, if we have a string like "Hello, World!", we mi
2 min read
Scraping And Finding Ordered Words In A Dictionary using Python
What are ordered words? An ordered word is a word in which the letters appear in alphabetic order. For example abbey & dirt . The rest of the words are unordered for example geeks The task at hand This task is taken from Rosetta Code and it is not as mundane as it sounds from the above descripti
3 min read
First and last character of each word in a String
Given a string s consisting of multiple words, print the first and last character of each word. If a word contains only one character, print it twice (since the first and last characters are the same).Note: The string will not contain leading or trailing spaces. Examples: Input: s = "Geeks for geeks
5 min read
Count occurrences of a word in string
You are given a string and a word your task is that count the number of occurrences of the given word in the string and print the number of occurrences of the word. Examples: Input : string = "GeeksforGeeks A computer science portal for geeks"word = "portal"Output : Occurrences of Word = 1 TimeInput
10 min read