'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
Solution 1:[1]
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])
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | mozway |
