求一段字符串中每个字符出现的次数,并排序输出(用Python实现)

统计字符串中每个字符的个数 排序输出结果

  • 将字符串去重存为列表
  • 将列表排序
  • 迭代列表 根据列表的值 去统计字符串中的字符
  • 将结果存储为字典
  • 输出结果

**

## 如果有更简单的方法请大佬评论告诉我,谢谢?

**

"""
求一个字符串 每个字符的个数。
"""
str1 = """
To be, or not to be—— that is the question;
Whether‘tis nobler in the mind to suffer
The slings and arrows of outrageous fortune,
Or to take arms against a sea of troubles,
And by opposing end them?
To die——to sleep——
No more; and by a sleep to say we end
The heart-ache and the thousand natural shocks
That flesh is heir to, 'tis a consummation
Devoutly to be wish'd.
"""
print("共%d个字符" % len(str1))

# 将字符串去重
set1 = set(str1)

# 将去重后的集合转换为列表并排序
list1 = list(set1)
list1.sort()

dict1 = dict()

# 迭代列表 并统计字符数 存入字典
for i in list1:
    num = str1.count(i)
    dict1.setdefault(i, num)

print(dict1)

输出结果为:

共370个字符
{’\n’: 11, ’ ‘: 60, "’": 2, ‘,’: 4, ‘-’: 1, ‘.’: 1, ‘;’: 2, ‘?’: 1, ‘A’: 1, ‘D’: 1, ‘N’: 1, ‘O’: 1, ‘T’: 5, ‘W’: 1, ‘a’: 22, ‘b’: 7, ‘c’: 3, ‘d’: 10, ‘e’: 33, ‘f’: 6, ‘g’: 4, ‘h’: 17, ‘i’: 14, ‘k’: 2, ‘l’: 8, ‘m’: 6, ‘n’: 19, ‘o’: 29, ‘p’: 4, ‘q’: 1, ‘r’: 15, ‘s’: 24, ‘t’: 29, ‘u’: 10, ‘v’: 1, ‘w’: 3, ‘y’: 4, ‘—’: 6, ‘‘’: 1}
Process finished with exit code 0

exit(⭐)

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值