python list ofwords.the program outputsthosewords&theirfrequencies.Ex:if the input is:hey hi Mark hi mark the output is: hey 1 hi 2 Mark 2 hi 2 mark 2

I thought I could use this code:

wordInput = input()

myList = wordInput.split(" ")

for i in myList:

   print(i,myList.count(i))

but its output is:

hey 1
Hi 1
Mark 1
hi 1
mark 1

How can I make it:

Hey 1
Hi 2
Mark 2
hi 2
mark 2

1 answer

  • answered 2022-05-07 05:50 mozway

    You need to convert your strings to a homogeneous format, for example lowercase.

    Also, the best is to first count the occurrences, then display (rather than searching and counting repeatedly).

    wordInput = 'hey hi Mark hi mark'
    
    words = wordInput.split()
    from collections import Counter
    counts = Counter(map(str.lower, words))
    
    for w in words:
        print(w, counts[w.lower()])
    

    Output:

    hey 1
    hi 2
    Mark 2
    hi 2
    mark 2
    

    Alternative that avoid computing twice the lowercase (but requires to store a lowercase copy of the list):

    wordInput = 'hey hi Mark hi mark'
    
    words = wordInput.split()
    words_lc = [w.lower() for w in words]
    from collections import Counter
    counts = Counter(words_lc)
    
    for w, w_lc in zip(words, words_lc):
        print(w, counts[w_lc])
    

How many English words
do you know?
Test your English vocabulary size, and measure
how many words do you know
Online Test
Powered by Examplum