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

如何用Python实现元音频率星号直方图及'the'计数功能

问题解决:元音统计直方图与"the"计数优化

需求说明

现有Python代码可统计输入句子中元音a/e/i/o/u的出现次数及单词"the"的出现次数,但无法将元音统计结果转换为对应数量的*生成直方图,且未处理无"the"时的输出逻辑。需要实现:

  • 每个元音单独一行,格式为「元音字母 + 对应数量的*」
  • 若句子中无"the",最后一行输出zero,否则输出其出现次数

修改后的代码

allowed_chars = set("abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ ")
string = input().strip()
# 验证输入字符合法性
if not set(string).issubset(allowed_chars):
    print("error")
else:
    # 初始化元音计数,用字典更简洁
    vowel_counts = {'a':0, 'e':0, 'i':0, 'o':0, 'u':0}
    # 统一转小写遍历,避免重复判断大小写
    for char in string.lower():
        if char in vowel_counts:
            vowel_counts[char] += 1
    
    # 输出元音直方图
    for vowel, count in vowel_counts.items():
        print(f"{vowel} {'*' * count}")
    
    # 统计"the"的出现次数,统一转小写匹配避免大小写问题
    the_count = 0
    for word in string.lower().split():
        if word == "the":
            the_count += 1
    
    # 处理"the"的输出逻辑
    print(the_count if the_count != 0 else "zero")

关键修改点

  • 简化元音统计:用字典存储元音计数,遍历前将字符串转小写,无需单独判断每个元音的大小写,代码更简洁易维护
  • 直方图输出:遍历元音计数字典,用'*' * count生成对应数量的星号,按要求格式输出
  • "the"计数优化:将字符串转小写后再分割单词,确保大小写形式的"the"都能被统计,并增加判断逻辑,无匹配时输出zero

示例验证

输入:this is a test count the vowels and how many the Is in the sentence
输出:

a ***
e ********
i ****
o ***
u *
3

若输入无"the"的句子(如hello world),最后一行输出zero

内容的提问来源于stack exchange,提问作者maria04

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.13 11:25:37