python统计单词出现次数

您所在的位置:网站首页 twinklelittlestar英文儿歌的乐句 python统计单词出现次数

python统计单词出现次数

2024-06-29 09:59| 来源: 网络整理| 查看: 265

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

 



【本文地址】


今日新闻


推荐新闻


CopyRight 2018-2019 办公设备维修网 版权所有 豫ICP备15022753号-3