Python打字测试:如何实现输入5个字符后自动提交无需按回车?
解决Python打字测试程序自动提交输入的问题
标准库的input()函数无法满足你的需求——它必须等待回车键触发输入结束,且默认支持退格修改。要实现输入5个按键后自动提交(无需回车),你需要用第三方库捕获单个按键输入,这里推荐getch库,它能直接读取终端按键,不需要回车确认。
实现步骤
- 安装
getch库:
pip install getch
- 修改代码,替换
input()为自定义按键捕获函数,实现5键自动提交、特殊按键处理及超时判断:
import time import random from getch import getch, getche def get_5_chars(timeout_end): input_chars = [] while len(input_chars) < 5: # 检查是否超时,超时则立即终止输入 if time.time() >= timeout_end: break # 捕获按键并实时回显 char = getche() # 处理箭头键(多字节输入,直接跳过) if ord(char) in [27, 91]: getch() getch() continue # 处理退格键:删除已输入的最后一个字符并更新终端显示 if ord(char) == 127: if input_chars: input_chars.pop() print('\b \b', end='', flush=True) continue input_chars.append(char) print() return ''.join(input_chars) t_end = time.time() + 60 # 设置60秒计时 correct = 0 incorrect = 0 wpm_count = 0 accuracy = 0 words=["buggy", "coder", "apple", "grape", "bread"] # 补充5字母单词列表 while time.time() < t_end: word = random.choice(words) print(word, end=" ") wpm_count += 1 user_txt = get_5_chars(t_end) # 超时导致的不完整输入不参与统计 if time.time() >= t_end: break if user_txt == word: correct += 1 else: incorrect += 1 # 计算并展示结果 if wpm_count > 0: accuracy = (correct / wpm_count) * 100 else: accuracy = 0 print("=-=-=- Results: -=-=-= ") print(f"Correct: {correct}") print(f"Errors: {incorrect}") print(f"Total Attempts: {wpm_count}") print(f"Accuracy: {accuracy:.2f}%")
关键改动说明
get_5_chars函数:负责捕获5次有效按键,处理退格的删除效果、跳过箭头键等无效输入,同时实时检查计时状态。- 替换
random.sample(words, 1)为random.choice(words),更简洁地获取单个随机单词。 - 修复原代码中
attempts变量未定义的问题,用wpm_count统计输入次数。 - 结果输出改用f-string格式化,提升可读性。
内容的提问来源于stack exchange,提问作者Slm Coding
相关产品推荐
相关产品推荐

