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

Python函数运行遇EOF错误:实现get_num_of_words后持续输入提示

问题说明

我正在完成大学课程项目,需实现多项功能需求。并非寻求未完成代码的完整解决方案,仅想解决调用get_num_of_words()函数后,如何持续提示用户输入且不触发EOF错误的问题。作业明确要求禁止使用现成函数。

现有代码

def get_num_of_words(user_input):
    count = 0
    words = 0
    length = 0
    for i in user_input:
        length += 1
    while count < length:
        if user_input[count] == user_input[-1]:
            words += 1
        elif user_input[count] != ' ' and user_input[count + 1] == ' ':
            words += 1
        else:
            pass
        count += 1
    print('Number of words:', str(words) + '\n')
    return words
    

def get_num_of_non_WS_characters(user_input):
    count = 0
    for i in user_input:
        if i == ' ':
            pass
        else:
            count += 1
    print('Number of non-whitespace characters:', str(count) + '\n')
    return count
    

def menu_prompt():
    print_menu()
    try:
        selection = input('Choose an option:\n')
        while selection != 'q' and selection != 'c' and selection != 'w' and selection != 'f' and selection != 'r' and selection != 's':
            selection = input('Choose an option:\n')
        return selection
    except EOFError:
        print('\n输入结束,退出程序')
        return 'q'
    
def execute_menu():
    user_input = input('Enter a sample text:\n')
    print()
    print('You entered:', user_input)
    print()
    while True:
        selection = menu_prompt()
        if selection == 'q':
            break
        elif selection == 'c':
            get_num_of_non_WS_characters(user_input)
        elif selection == 'w':
            get_num_of_words(user_input)
        # 后续功能可在此补充
        # elif selection == 'f':
        #     调用对应函数
        # elif selection == 'r':
        #     调用对应函数
        # elif selection == 's':
        #     调用对应函数
        
def print_menu():
    print('MENU\nc - Number of non-whitespace characters\nw - Number of words\nf - Fix capitalization\nr - Replace punctuation\ns - Shorten spaces\nq - Quit\n')
    
    
if __name__ == '__main__':
    try:
        execute_menu()
    except EOFError:
        print('\n输入结束,退出程序')

解决要点

  • 替换递归为循环结构:原代码用递归调用execute_menu维持菜单循环,递归次数过多会触发栈溢出风险,改成while True循环更稳定,也更易控制退出逻辑。
  • 捕获EOFError异常:用户输入EOF(Windows下Ctrl+Z、Linux/macOS下Ctrl+D)时会触发该异常,在menu_prompt和主入口处添加捕获逻辑,避免程序崩溃,同时给出提示并退出。
  • 保留原有功能逻辑:未改动get_num_of_words和get_num_of_non_WS_characters的实现,符合不想修改已有正确功能的需求。

如果需要支持用户重新输入文本,可在菜单新增选项(比如n - 输入新文本),在execute_menu的循环内处理该选项,重新获取user_input即可。

内容的提问来源于stack exchange,提问作者Mr.Moffia

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.08 20:25:17