Python word frequency counter

advertisements

Struggling with this exercise which must use a dictionary and count the number of times each word appears in a number of user inputs. It works in a fashion, but does not atomise each word from each line of user input. So instead of counting an input of 'happy days' as 1 x happy and 1 x days, it gives me 1 x happy days. I have tried split() along with the lower() but this converts the input to a list and I am struggling with then pouring that list into a dictionary.

As you may have guessed, I'm a bit of a novice, so all help would be greatly appreciated!

occurrences = {}
while True:
    word = input('Enter line: ')
    word = word.lower() #this is also where I have tried a split()
    if word =='':
        break
occurrences[word]=occurrences.get(word,0)+1
for word in (occurrences):
    print(word, occurrences[word])

EDIT

Cheers for responses. This ended up being the final solution. They weren't worried about case and wanted the final results sorted().

occurrences = {}
while True:
    words = input('Enter line: ')
    if words =='':
        break
    for word in words.split():
        occurrences[word]=occurrences.get(word,0)+1
for word in sorted(occurrences):
    print(word, occurrences[word])


What you have is almost there, you just want to loop over the words when adding them to the dict

occurrences = {}
while True:
    words = input('Enter line: ')
    words = words.lower() #this is also where I have tried a split()
    if words =='':
        break
    for word in words.split():
        occurrences[word]=occurrences.get(word,0)+1
    for word in (occurrences):
        print(word, occurrences[word])