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

Python实现文本单词连续元音计数 现有错误代码修复求助

代码问题修复与功能实现

原有代码问题梳理

  • openFile函数缩进混乱,冗余执行infile.readline()会丢失文件第一行内容,未主动关闭打开的文件句柄
  • findVowels函数逻辑错误:if word == "a" or "e" or "i" or "o" or "u"的写法永远返回True,且函数仅判断是否存在元音,完全没有连续计数的能力,额外执行的split()操作对传入的单个单词无意义
  • main函数缩进错误,打印语句放在循环外只会输出最后一个单词的结果,计数逻辑完全不符合连续元音统计的需求

修复后可运行代码

def openFile(fileName):
    words = []
    # 用with上下文自动管理文件关闭,避免资源泄漏
    with open(fileName, "r") as infile:
        for data in infile:
            dataStrip = data.strip('\n')
            # 跳过空行
            if dataStrip:
                words.append(dataStrip)
    return words

def count_consecutive_vowels(word):
    vowels = {'a', 'e', 'i', 'o', 'u'}
    max_count = 0
    current_count = 0
    # 遍历单词的每个字符
    for char in word.lower(): # 统一转小写,兼容大写元音的情况
        if char in vowels:
            current_count += 1
            # 更新最大连续数
            if current_count > max_count:
                max_count = current_count
        else:
            # 遇到非元音,重置当前连续计数
            current_count = 0
    return max_count

def main():
    file_words = openFile("vowels.txt")
    for word in file_words:
        vowelCount = count_consecutive_vowels(word)
        print(f"{word} has {vowelCount} consecutive vowels in it")

main()

功能说明

  • 自动读取vowels.txt中每行的单词,自动跳过空行
  • 不区分元音大小写,大小写元音都会被统计
  • 输出每个单词对应的最长连续元音数量

内容的提问来源于stack exchange,提问作者Mafia Feline Boss

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.25 19:54:04