Python-词频统计练习(Counter)

统计文件中出现的每个单词的次数,找出出现次数最多的5个单词

# 1.加载文件中所有的单词
with open('venv/song.txt',mode='r') as f:
    word = f.read()
words = word.split(' ')
# 2.统计
d = {}
for i in words:
    if i in d:
        d[i] = d[i] + 1
    else:
        d[i] = 1
print(d)

找出现最多的单词数可用counter

with open('venv/song.txt',mode='r') as f:
    word = f.read()
words = word.split(' ')
from collections import Counter
counter = Counter(words)            #使用Couner统计单词出现的次数
result = counter.most_common(5)     #找出出现次数前五多的单词
print(result)

你可能感兴趣的:(python,数据结构,开发语言)