python统计单词出现次数

统计英文儿歌《twinkle twinkle little star》中,使用到的单词及其出现次数。要求去除单词大小写的影响,不统计标点符号的个数,并按降序输出。

Twinkle, twinkle, little star,

How I wonder what you are!

Up above the world so high,

Like a diamond in the sky.

Twinkle, twinkle, little star,

How I wonder what you are!

When the blazing sun is gone,

When he nothing shines upon,

Then you show your little light,

Twinkle, twinkle, all the night.

Twinkle, twinkle, little star,

How I wonder what you are!

题干说去除大小写,不统计标点,所以第一部先把大写转小写并且把标点符号转换成空格;然后用split函数将字符串切片,返回一个字符串列表;接着统计列表中各元素出现次数,整合到一个字典里;最后用sorted对字典的值进行排序。

message = "Twinkle, twinkle, little star,How I wonder what you are!" \
          "Up above the world so high,Like a diamond in the sky." \
          "Twinkle, twinkle, little star,How I wonder what you are!" \
          "When the blazing sun is gone,When he nothing shines upon," \
          "Then you show your little light,Twinkle, twinkle, all the night." \
          "Twinkle, twinkle, little star,How I wonder what you are!"
message = message.lower().replace(',', ' ').replace('.', ' ').replace('!', ' ')
list_message = message.split()
count = {}
for i in list_message:
    if i not in count:
        count[i] = 1
    else:
        count[i] += 1
print(sorted(count.items(), key=lambda item: item[1], reverse=True))

运行结果: 

[('twinkle', 8), ('little', 4), ('you', 4), ('the', 4), ('star', 3), ('how', 3), ('i', 3), ('wonder', 3), ('what', 3), ('are', 3), ('when', 2), ('up', 1), ('above', 1), ('world', 1), ('so', 1), ('high', 1), ('like', 1), ('a', 1), ('diamond', 1), ('in', 1), ('sky', 1), ('blazing', 1), ('sun', 1), ('is', 1), ('gone', 1), ('he', 1), ('nothing', 1), ('shines', 1), ('upon', 1), ('then', 1), ('show', 1), ('your', 1), ('light', 1), ('all', 1), ('night', 1)]

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值