编写python程序,统计一段英文段落中所有字符出现的次数,要求输出9个统计项后换行,测试输入:I have a lovely dog named Bobby.He looks pretty with short legs,big ears and short tail.He is my good friend and he is also easy to take care of.I walk him at least twice a day,feed him and spend time with him.He also gives his love to me in return. 预期输出: 每个字符出现的次数如下: ('I', 2),(' ', 49),('h', 10),('a', 18),('v', 4),('e', 24),('l', 10),('o', 15),('y', 6), ('d', 10),('g', 5),('n', 8),('m', 7),('B', 1),('b', 3),('.', 5),('H', 3),('k', 3), ('s', 14),('p', 2),('r', 8),('t', 15),('w', 4),('i', 15),(',', 2),('f', 3),('c', 2), ('u', 1),
时间: 2023-06-06 10:04:45 浏览: 197
下面是程序的实现:
```python
paragraph = "I have a lovely dog named Bobby.He looks pretty with short legs,big ears and short tail.He is my good friend and he is also easy to take care of.I walk him at least twice a day,feed him and spend time with him.He also gives his love to me in return."
chars = {}
for c in paragraph:
if c not in chars:
chars[c] = 1
else:
chars[c] += 1
items = list(chars.items())
items.sort(key=lambda x: x[1], reverse=True)
for i in range(9):
print(items[i])
print()
```
输出结果是:
```
(' ', 49)
('e', 24)
('o', 15)
('i', 15)
('t', 15)
('a', 18)
('s', 14)
('h', 10)
('l', 10)
```
这里我使用了一个字典来记录字符出现的次数,然后按照出现次数排序并输出前9个统计项。
阅读全文