统计单词个数(忽略大小写)

统计英语儿歌《twinkle twinkle little star》中使用到的单词及出现的次数。

儿歌《twinkle twinkle little star》
Twinkle, twinkle, littlestar,
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!
Then the travler in the dark
Thanks you for your tiny spark;
How could he see where to go,
If you did not twinkle so?
Twinkle, twinkle, little star,
How I wonder what you are!
In the dark blue sky you keep, and
Through my curtains often peep,
For you never shut your eyes,
Till the morning sun does rise.
Twinkle, twinkle, little star,
How I wonder what you are!
As your bright and tiny spark
Lights the travler in the dark,
Though I know not what you are,
Twinkle on, please, little star.
Twinkle, twinkle, little star,
How I wonder what you are!

工具pycharm,利用Python中的的字典

实现代码如下

# 歌词统计
import re

str = "Twinkle, twinkle, littlestar,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!Then the travler in the darkThanks you for your tiny spark;How could he see where to go,If you did not twinkle so?Twinkle, twinkle, little star,How I wonder what you are!In the dark blue sky you keep, andThrough my curtains often peep,For you never shut your eyes,Till the morning sun does rise.Twinkle, twinkle, little star,How I wonder what you are!As your bright and tiny sparkLights the travler in the dark,Though I know not what you are,Twinkle on, please, little star.Twinkle, twinkle, little star,How I wonder what you are!"
# 切分字符,并转化成小写
s_list = re.split('[^a-zA-Z]', str.lower())
# 除去空格
r_list = list(filter(None, s_list))
# 定义一个字典
dictionary = {}
for l in r_list:
    count = 0;
    for s in r_list:
        if l == s:
            count = count + 1
    dictionary[l] = count

# 字典按key从大到小排序
sort_list = sorted(dictionary.items(), key=lambda e: e[1], reverse=True)
# 遍历
for s in sort_list:
    print('%s 出现了%d次' % (s[0], s[1]))
  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值