24 lines
726 B
Python
24 lines
726 B
Python
words = ["look", "into", "my", "eyes", "look", "into", "my", "eyes",
|
|
"the", "eyes", "the", "eyes", "the", "eyes", "not", "around", "the",
|
|
"eyes", "don't", "look", "around", "the", "eyes", "look", "into",
|
|
"my", "eyes", "you're", "under"]
|
|
|
|
# collect里面的Counter库可以帮我们计数
|
|
from collections import Counter
|
|
|
|
word_counts = Counter(words)
|
|
top_three = word_counts.most_common(3)
|
|
print(top_three)
|
|
|
|
# Counter的底层是一个字典,是一个DefaultDict,这里处于学习目的把它实现一遍
|
|
from collections import defaultdict
|
|
|
|
def counter(word_list):
|
|
counter = defaultdict(int)
|
|
for word in word_list:
|
|
counter[word] += 1
|
|
|
|
return counter
|
|
|
|
print(counter(words))
|
|
|