编写程序,统计字符串中每个字符出现的次数,并计算所占百分比。(利用字典的get函数 和Counter函数分别实现) import string xstr=string.digits+string.asci_letters+string.punctuation
时间: 2024-10-24 22:15:17 浏览: 13
编写Python程序,你可以使用`collections.Counter`函数轻松统计字符串中每个字符及其出现次数,以及计算所占百分比。这里有两个方法,一个是直接使用`Counter`,另一个是结合`get`函数。
**方法一:使用Counter**
```python
from collections import Counter
xstr = string.digits + string.ascii_letters + string.punctuation
char_counts = Counter(xstr)
# 统计每个字符出现的次数
char_frequency = {char: count for char, count in char_counts.items()}
# 计算所占百分比
total_chars = sum(char_counts.values())
percentage_dict = {char: (count / total_chars) * 100 for char, count in char_frequency.items()}
print("每个字符的出现次数:", char_frequency)
print("每个字符的百分比:", percentage_dict)
```
**方法二:使用字典的get函数**
```python
xstr = string.digits + string.ascii_letters + string.punctuation
char_frequency = {}
for char in xstr:
char_frequency[char] = char_frequency.get(char, 0) + 1 # 如果键不存在,返回默认值0并加1
# 计算总字符数
total_chars = len(xstr)
# 转换为百分比
percentage_dict = {char: (freq / total_chars) * 100 for char, freq in char_frequency.items()}
print("每个字符的出现次数:", char_frequency)
print("每个字符的百分比:", percentage_dict)
```
阅读全文