python-统计文件中单词出现次数

# 菜鸟出没
# 非战斗人员请撤离
# 时间:2022/3/16 19:21

#统计一个文件中单词出现的次数,并输出出现次数最多的前3个单词
def countword(file):
    fp = open(file, mode='r', encoding='utf-8')
    word_l = {}
    for line in fp:
        sword = line.strip().split()
        for word in sword:
            if word in word_l:
                word_l[word]+=1
            else:
                word_l[word] = 1
    word_list = sorted(word_l.items(), key=lambda e: e[1], reverse=True)
    for i,j in word_list[:3]:
        print((j,i))


file = input()
countword(file)

你可能感兴趣的:(python)