Frequent word count code

Write a python program that accepts a text and displays a string which contains the word with the largest frequency in the text and the frequency itself separated by a space.


Rules:

  1. The word should have the largest frequency.

  2. In case multiple words have the same frequency, then choose the word that has the maximum length.

Assumptions:

  1. The text has no special characters other than space.

  2. The text would begin with a word and there will be only a single space between the words.

Perform case insensitive string comparisons wherever necessary.



SOLUTION:



def max_frequency_word_counter(data):
word=""
frequency=0
data=data.lower() #for lowercase the sentence
lt=data.split() #split sentence in words
for e in lt:
freq=lt.count(e) #count the occurrence
if freq > frequency :
frequency=freq
word=e
elif freq == frequency :
if len(e) > len(word) :
frequency=freq
word=e
print(word,frequency)
data = "Work like you do not need money, love like your have never your been hurt, and dance like no one is watching"
max_frequency_word_counter(data)

Post a Comment

0 Comments