Python——统计字符串中每个字符出现的次数

Python——统计字符串中每个字符出现的次数

代码如下:

"""
作者:DELL
日期:2020年 06月 23日
"""
import pprint
message = '''I offer you lean streets, desperate sunsets, the moon of the jagged suburbs. 
             I offer you the bitterness of a man who has looked long and long at the lonely moon. 
             I offer you my ancestors, my dead men, the ghosts that living men have honoured in marble: 
             my father’s father killed in the frontier of Buenos Aires, two bullets through his lungs, 
             bearded and dead, wrapped by his soldiers in the hide of a cow;  
             my mother’s grandfather -just twenty-four- heading a charge of three hundred men in Perú, 
             now ghosts on vanished horses. 
             I offer you whatever insight my books may hold. whatever manliness or humour my life. 
             I offer you the loyalty of a man who has never been loyal. 
             I offer you that kernel of myself that I have saved somehow -the central heart that deals not in words, 
             traffics not with dreams and is untouched by time, by joy, by adversities. 
             I offer you the memory of a yellow rose seen at sunset, years before you were born. 
             I offer you explanations of yourself, theories about yourself, authentic and surprising news of yourself. 
             I can give you my loneliness, my darkness, the hunger of my heart; 
             I am trying to bribe you with uncertainty, with danger, with defeat.'''
count = {}#用字典来存放结果
for i in message:#遍历整个字符串
    count.setdefault(i,0)#如果第一次出现就设置次数为默认0
    count[i]+=1
    pass
    
pprint.pprint(count)

运行结果如下:
Python——统计字符串中每个字符出现的次数_第1张图片
Mission all over

你可能感兴趣的:(Python,python)