A Python Program to Count the Occurrences of Each Word in a Given String Sentence and stores the count in a dictionary e.g {‘so’:1}

--

Say you have an input strings from user, where user is asked to enter sentence of his or her choice. You can count the occurrences of each word in the sentence using python dictionaries as explained below.

user_input = input(“Enter your sentence here separated with space: “) #request user input

sentence = user_input.split() # split the user input

text = set(sentence) # obtain the unique word from the sentence

dict_sentence = {} #declare an empty dictionary

for i in text:

count = user_input.count(i)

dict_sentence.update({i:count})

print(dict_sentence)

Please comment on this post for improvement in my future post

#techbridge consulting

--

--

No responses yet