You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python列表与循环:字符串字符统计格式化输出求助

问题修正方案

你的代码存在两个核心问题:

  1. 已经将文本转为小写,但遍历统计时仍使用原文本,导致大小写字符被分别统计(比如原文本的Y和y会被算作两个不同字符)
  2. 没有过滤空格、逗号、句号等非字母字符,且输出格式不符合要求

修改后的代码如下:

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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.16 13:50:24