Python列表与循环:字符串字符统计格式化输出求助
问题修正方案
你的代码存在两个核心问题:
- 已经将文本转为小写,但遍历统计时仍使用原文本,导致大小写字符被分别统计(比如原文本的
Y和y会被算作两个不同字符) - 没有过滤空格、逗号、句号等非字母字符,且输出格式不符合要求
修改后的代码如下:
from collections import defaultdict text = 'You can have data without information, but you cannot have information without data.' lower_case_text = text.lower() chars = defaultdict(int) # 遍历小写后的文本,仅统计字母字符 for char in lower_case_text: if char.isalpha(): chars[char] += 1 # 按字母顺序排序后输出指定格式 for char in sorted(chars.keys()): print(f"{char} : {chars[char]}")
执行后会得到符合预期的输出:
a : 10 b : 1 c : 2 d : 2 e : 2 f : 2 h : 4 i : 6 m : 2 n : 7 o : 9 r : 2 t : 10 u : 5 v : 2 w : 2 y : 2
内容的提问来源于stack exchange,提问作者Damion Pointin
相关产品推荐
相关产品推荐

