Python之统计英文字符的个数

一、统计英文字符的个数

二、计数函数——Counter


一、统计英文字符的个数

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

from collections import Counter
sing = "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!"
# 处理字符串
lsing = sing.lower()    # 将大写字母改成小写字母
a_sing = lsing.replace(',',' ')   # 将逗号换成空格
b_sing = a_sing.replace('!',' ')  # 将感叹号换成空格
c_sing = b_sing.replace('.',' ')  # 将句号换成空格
d_sing = c_sing.split()        # 去掉空格
# 统计
dict_sing = Counter(d_sing)
for k,v in sorted(dict_sing.items(),key = lambda x:x[1],reverse=True):
    print(k,v)

二、计数函数——Counter

1、举例

colors = [{'red':4},{'blue':5},{'red':8},{'green':7},{'blue':8},{'blue':10},{'green':12}]

方法一——使用比较传统的循环方法:

colors = [{'red':4},{'blue':5},{'red':8},{'green':7},{'blue':8},{'blue':10},{'green':12}]
result = {}
for i in colors:
    if list(i.keys())[0] not in result:
        result[list(i.keys())[0]] = list(i.values())[0] 
    else:
        result[list(i.keys())[0]] += list(i.values())[0]
print(result)

# 结果为:{'red': 12, 'blue': 23, 'green': 19}

方法二——Counter函数:

from collections import Counter
colors = [{'red':4},{'blue':5},{'red':8},{'green':7},{'blue':8},{'blue':10},{'green':12}]
c = Counter()
for i in colors:
    c[list(i.keys())[0]] += list(i.values())[0]
print(c)

# 结果为:Counter({'blue': 23, 'green': 19, 'red': 12})
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值