python中统计各个字母出现的次数-Python统计字母出现的频率

使用 Python 统计 26 个字母出现的频率:输入是一个很长的字符串,对其中的英文字母统计其出现的次数,其他字符忽略不处理,大写字母和小写字母当作一个字母来看。

input_str = """The First-ever Open-water

Beluga Sanctuary Will Welcome Two Adorable Whales in June,

Adorable beluga whales are a popular attraction to aquariums

around the world, but like many other wild animals,

they also risk losing their habitats due to human

intervention such as population growth, new buildings

along the coastline, fishing, and other problems

that sea creatures face.

""" # 输入的字符串

def calc_statistic(input_str): # 计算英文字母出现的频率

result = [0] * 26 # 构建结果列表

for c in input_str: # 对于每个输入字符串中的字符

if c.isalpha(): # 必须是26*2个字符之一

c = c.lower() # 统一转换成小写字符

index = ord(c) - ord("a") # 计算出其对应的位置

result[index] = result[index] + 1 # 将出现的次数加一

for ele in range(0, 26): # 显示打印结果

c = chr(ord("a") + ele) # 将位置转换成字符

print("[%s] Shows Up %d Times" % (c, result[ele])) # 显示结果

calc_statistic(input_str) # 进行处理

输出结果如下:

$ python calcCharFreq.py

[a] Shows Up 35 Times # a字符出现的次数

[b] Shows Up 8 Times # b字符出现的次数

[c] Shows Up 7 Times

[d] Shows Up 8 Times

[e] Shows Up 32 Times # e字符出现的次数

[f] Shows Up 3 Times

[g] Shows Up 7 Times

[h] Shows Up 15 Times

[i] Shows Up 20 Times

[j] Shows Up 1 Times

[k] Shows Up 2 Times # k字符出现的次数

[l] Shows Up 21 Times

[m] Shows Up 6 Times

[n] Shows Up 20 Times

[o] Shows Up 22 Times

[p] Shows Up 6 Times

[q] Shows Up 1 Times

[r] Shows Up 21 Times

[s] Shows Up 18 Times

[t] Shows Up 27 Times

[u] Shows Up 15 Times

[v] Shows Up 2 Times

[w] Shows Up 10 Times

[x] Shows Up 0 Times

[y] Shows Up 3 Times

[z] Shows Up 0 Times # z字符出现的次数

  • 8
    点赞
  • 29
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值