In: Computer Science
5. Take user input and give corresponding output.
User will enter a sentence. The program will output the word that appears most frequently in this sentence. If there are multiple words with same frequency, output the first of these words.
Please enter a sentence: I like batman because batman saved the city many times. The most frequent word is: batman The frequency is: 2
PYTHON
Python code:
#initializing the dictionary called words to store all
words
words={}
#obtaining the sentence and spliting it
line=input("Please enter a sentence: ").split()
#looping each word in line
for i in line:
#adding word and its count to words
words[i]=line.count(i)
#prints the word with maximum count
print("The most frequent word is:",max(words,key=words.get))
#printing its count
print("The frequency is:",words[max(words,key=words.get)])
Screenshot:
Input and Output: