Python之统计英⽂字符的个数
⼀、统计英⽂字符的个数
统计英⽂⼉歌《twinkletwinklelittlestar》中,使⽤到的单词及其出现次数。
要求去除单词⼤⼩写的影响,不统计标点符号的个数。并按降序输出。
Twinkle,twinkle,littlestar,HowIwonderwhatyouare!Upabovetheworldsohigh,e,twinkle,
littlestar,HowIwonderwhatyouare!Whentheblazingsunisgone,Whenhenothingshinesupon,Thenyoushowyourlittle
light,
Twinkle,twinkle,e,twinkle,littlestar,HowIwonderwhatyouare!
fromcollectionsimportCounter
sing="Twinkle,twinkle,littlestar,
HowIwonderwhatyouare!
Upabovetheworldsohigh,
Likeadiamondinthesky.
Twinkle,twinkle,littlestar,
HowIwonderwhatyouare!
Whentheblazingsunisgone,
Whenhenothingshinesupon,
Thenyoushowyourlittlelight,
Twinkle,twinkle,allthenight.
Twinkle,twinkle,littlestar,
HowIwonderwhatyouare!"
#处理字符串
lsing=()#将⼤写字母改成⼩写字母
a_sing=e(',','')#将逗号换成空格
b_sing=a_e('!','')#将感叹号换成空格
c_sing=b_e('.','')#将句号换成空格
d_sing=c_()#去掉空格
#统计
dict_sing=Counter(d_sing)
fork,vinsorted(dict_(),key=lambdax:x[1],rever=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={}
foriincolors:
iflist(())[0]notinresult:
result[list(())[0]]=list(())[0]
el:
result[list(())[0]]+=list(())[0]
print(result)
#结果为:{'red':12,'blue':23,'green':19}
⽅法⼆——Counter函数:
fromcollectionsimportCounter
colors=[{'red':4},{'blue':5},{'red':8},{'green':7},{'blue':8},{'blue':10},{'green':12}]
c=Counter()
foriincolors:
c[list(())[0]]+=list(())[0]
print(c)
#结果为:Counter({'blue':23,'green':19,'red':12})
本文发布于:2022-12-09 15:56:01,感谢您对本站的认可!
本文链接:http://www.wtabcd.cn/fanwen/fan/88/73438.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
留言与评论(共有 0 条评论) |