-1

Write a program that reads a list of words. Then, the program outputs those words and their frequencies.

Ex: If the input is:

hey hi Mark hi mark

the output is:

hey 1
hi 2
Mark 1
hi 2
mark 1

Here's what I tried:

list = 'hey hi Mark hi mark'
text = list.split()

for word in text:
        freq = text.count(word) 
        print(*text, freq)
MrGeek
  • 19,520
  • 4
  • 24
  • 49
John
  • 21
  • 1
  • 4
  • 1
    What is your question? – Pac0 May 17 '20 at 22:07
  • What is your expected output? What you have here is correct, even if words like "hi" are repeated. – bnaecker May 17 '20 at 22:07
  • Please repeat [how to ask](https://stackoverflow.com/help/how-to-ask) from the [intro tour](https://stackoverflow.com/tour). We expect you to research the topic before you post here -- and to give a complete problem description. – Prune May 17 '20 at 22:14

2 Answers2

0

The Counter class is useful for stuff like this:

>>> sentence = 'hey hi Mark hi mark'
>>> from collections import Counter
>>> print(Counter(sentence.split()))
Counter({'hi': 2, 'hey': 1, 'Mark': 1, 'mark': 1})

or:

>>> for word in sentence.split():
...     print(f"{word} {Counter(sentence.split())[word]}")
...
hey 1
hi 2
Mark 1
hi 2
mark 1
Samwise
  • 32,741
  • 2
  • 21
  • 31
0

you just need to replace

print(*text, freq)

to

print(word, freq)

You want to print just the word, not the full text

The output is going to be

hey 1
hi 2
Mark 1
hi 2
mark 1
João Castilho
  • 438
  • 2
  • 19