统计英语儿歌《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]))