一、统计英文字符的个数
统计英文儿歌《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})