Python Word频率[重复]

编写一个读取单词列表的程序。然后,程序输出这些单词及其频率。

例如:如果输入是:

hey hi Mark hi mark

输出为:

hey 1
hi 2
Mark 1
hi 2
mark 1

这是我尝试过的:

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

for word in text:
        freq = text.count(word) 
        print(*text, freq)
评论
执着
执着

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})

要么:

>>> for word in sentence.split():
...     print(f"{word} {Counter(sentence.split())[word]}")
...
hey 1
hi 2
Mark 1
hi 2
mark 1
点赞
评论
tvelit
tvelit

您只需要更换

print(*text, freq)

print(word, freq)

您只想打印单词,而不是全文

点赞
评论