count the number of occurences of each word in the text

Viewed 25

I am trying to count the number of count of occurrence of each word in a text, I have below code but it seems that it is not jumping to the else part of my loop

text = "Joy is joy but joy is not finding a solution"
x= {}
for mot in text.lower().split():
  if x.get(mot) not in x.keys():
    print(mot)
    x[mot] = 1
    print(x[mot])
  else :
    print("the word is" + mot)
    x[mot] = (x[mot]+1)
    print((x[mot]))
  print(x)

x

Any help appreciated to resolve it with an if loop

1 Answers

You are checking wrong condition in if statement, when you call get method and pass it a key it returns its value, which means you are checking for value of that key in the keys of that dictionary. Its working solution could be:

text = "Joy is joy but joy is not finding a solution" 
x= {}
for mot in text.lower().split(): 
    if mot not in x.keys(): 
        x[mot] = 1 
    else:
        x[mot] += 1

print(x)
Related