字典get方法和setdesault方法,统计message中各元素的出现频次

message= 'There are moments in life when you miss someone so much that you just want to pick them from your dreams and hug them for real! Dream what you want to dream;go where you want to go;be what you want to be,because you have only one life and one chance to do all the things you want to do.'
#方法一:setdefault方法,输出字母数
#dict.setdefault(key, default=None) 有key获取值、没key设置 key:default。
count1={}
for i in message:
count1.setdefault(i,0) # 查询此次计数前此字母出现的次数,没有就添加key,值为0.
count1[i] = count1[i]+1 #更新次数(for每次遍历一个字母,故次数加一) .
      #上面两段代码可简化为:count1[i]=count1.setdefault(i,0)+1
print('>>>',count1)

#方法二:# get方法
# dict.get(key, default=None) 有key获取值、没key返回default。
count2={}
for i in message:
count2[i]=count2.get(i,0)+1
print('>>>',count2)

#方法三:Count方法:统计各元素出现的频次,并转化成字典输出。
# 统计单词数,要用re模块中的split函数来分割成单词。
import re
from collections import Counter
lis2=re.split('[ ,.;!]',message) # re模块中的split函数,可以处理多个分隔符。字符串中的只能处理一个分隔符。
print(dict(Counter(lis2))) #输出每个单词出现的频次,记得转成字典。
print(
max(set(lis2),key=lis2.count), #输出频次最多的字母。
lis2.count(max(set(lis2),key=lis2.count)) #输出频次最多的字母的个数。
)
原文地址:https://www.cnblogs.com/qqq789001/p/14243644.html