用Python进行统计单词个数

在这里我们用字典来实现,首先读取一个文件中的字符串,去掉标点符号以及空格存到word列表中,在写入字典中根据count方法读取某个单词出现的个数。不明白这个counts方法的可以去看这篇文章https://blog.csdn.net/weixin_42800007/article/details/82024108

代码:

def create_file():
 with open("my.txt",'w') as g_file:
    g_file.write('while there is life,there is hope')
create_file()
def get_txt():
    with open("my.txt",'r') as g_file:
        str = g_file.readline()
        return str
lines = get_txt()
print(lines)
for ch in ',*.':#将字符串中的,* .替换为空格
    lines = lines.replace(ch," ")
words = lines.split()#去掉空格,将字符串中的单词提取出来

counts = {}#创建一个空的字典
for word in words:
    counts[word] = counts.get(word,0)+1
print(counts)
items = list(counts.items())#将字典中的每对键值对看做一个元素存入items列表中
items.sort(key=lambda x:x[1],reverse=True)
#根据lambda表达式来进行排序 在这里是根据数字来排序
for i in range(len(items)):
    word,count = items[i]
    print(word,count)

输出结果:

there 2
is 2
while 1
life 1
hope 1

 

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值