Python Program to Find The Second Most Repeated Word in a Given String

In this article let's learn how to find the second most repeated word in a given string using python Program. Let's take an Empty dictionary and store the  words present in a string as keys of the dictionary,  and the value of the dictionary is the number of times the word has occurred in a string.

Once we find the dictionary containing words and values as number of times the  word has occurred let's start the dictionary and print the second most repeated word in a string.

 

Write a Python Program to Find The Second Most Repeated Word in a Given String

 

 


Write a Python Program to Find The Second Most Repeated Word in a Given String

Take a string variable named as text,  asking the user to enter a string,  convert the list containing words using split() function call.  Take an Empty dictionary Variable name as freq,  and initialize it to empty


text = input("Enter a String : ")
words = text.split(" ")
freq = dict()




Now iterate all the words present in the String using the word look and check if a word is present in a dictionary if so increment the value.  if the word has occurred first time then initialize the value to 1.

for word in words:
   if word in freq:
       freq[word] += 1
   else:
       freq[word] = 1




Once it is completed we will be having a key value pair containing words and number of times word has repeated in a dictionary.  start the dictionary based on value in descending order using sorted function calls. Using the print function, call print the second  most repeated word by referring to index 1 of the  sorted dictionary.

freq_list = sorted(freq, key=freq.get, reverse=True)
print("The Second Most Repeated Word in a Given String : ", freq_list[1])


Python program
=========================

text = input("Enter a String : ")
words = text.split(" ")

freq = dict()
for word in words:
   if word in freq:
       freq[word] += 1
   else:
       freq[word] = 1


freq_list = sorted(freq, key=freq.get, reverse=True)
print("The Second Most Repeated Word in a Given String : ", freq_list[1])





Output
================
>python main.py
Enter a String : aa bb cc aa aa bb
The Second Most Repeated Word in a Given String :  bb





Output 2
===================
>python main.py
Enter a String : h e l l o w o r l d
The Second Most Repeated Word in a Given String :  o





Conclusion
==================
Execute the above Python program by providing a random string as input and note down the results.

Comment it down below  if you have any queries are suggestions to improve the above p python program.


Post a Comment

0 Comments