python小试牛刀------查找文件中各单词出现的次数并字典方式打印(Counter模块自动计数、自动排序并以字典方式呈现)

文件内容:

cry on my shoulder
but if you wanna cry
cry on my shoulder
if you need someone who cares for you
if you are feeling sad your heart gets colder
yes i show you what real love can do

代码实现:

with open('doc.txt') as f:
    content = f.read().split()
    content1=set(content)
    print(content1)
    b = {}
    for i in content1:
        count = 0
        for a in content:
            if a==i:
                count+=1
            else:
                continue
        b[i]=count
    print(b)

运行结果:
在这里插入图片描述

另一种简单的方法:

with open('doc.txt') as f:
    content = f.read().split()
    b = {}
    for i in content:
        if i in b:
            b[i]+=1
        else:
            b[i]=1
import  pprint       ##换行打印
pprint.pprint(b)

运行结果:
在这里插入图片描述
利用第三方模块实现:

from collections import Counter
with open('doc.txt') as f:
    content = f.read().split()
    count = Counter(content)  ###调用Counter函数自动计数并打印
    print(count)

运行结果:
在这里插入图片描述
Counter模块还可以进行自动排序:

from collections import Counter
with open('doc.txt') as f:
    content = f.read().split()
    count = Counter(content)
    result = count.most_common(5)   ###自动排序,并显示前5print(result)

运行结果:
在这里插入图片描述

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值