如何在PyInputPlus.inputStr()函数中获取与BlockRegex匹配的输入值

2024-09-28 20:42:51 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个来自automate book的简单乘法测验,我想对它进行扩展。 我的目标是收集错误答案,并在游戏结束时显示它们。 但是,代码检查正确答案的方法是使用blockRegexes参数阻塞除正确答案之外的所有内容。 我已尝试检查验证异常,但不起作用

这是我的密码:

import pyinputplus as p
import random, time

numberOfQuestions = 10
correctAnswers = 0
incorrectAnswers = []

#def blockRegRaiseExcep(text):
    # because in a regular inputStr it won't raise an exception if I match the blocked regex.
for questionNumber in range(numberOfQuestions):

    # Pick two random numbers:
    num1 = random.randint(0,9)
    num2 = random.randint(0,9)

    prompt = f'#{questionNumber}: {num1} x {num2} = '

    try:
        # Right answers are handled by allowRegexes.
        # Wrong answers are handled by blockRegexes, with a custom message.
        inp = p.inputStr(prompt,allowRegexes=[f'^{num1 * num2}$'], # allow only the right number! great.
                         blockRegexes=[('.*','Incorrect!')], # we are blocking everything, basically, love it!
                         timeout=8, limit=3)

    except p.TimeoutException:
        print(f'Out of time!\nCorrect answer is {num1 * num2}')
        
    except p.RetryLimitException:
        print(f'Out of tries!\nCorrect answer is {num1 * num2}')
    else:
        # This block runs if no exceptions were raised by the try block.
        print('Correct!')
        correctAnswers += 1

    time.sleep(1) # Brief pause to let the user read the result.

print(f'Score: {correctAnswers} / {numberOfQuestions}')

Tags: the答案inimportbytimerandomare
1条回答
网友
1楼 · 发布于 2024-09-28 20:42:51

实际上,你可以通过不同的方式实现你想要的

  1. 有一个可选参数applyFunc,它是所有input*()函数的公共参数,请参见documentation或调用help(pyip.parameters)

    applyFunc (Callable, None): An optional function that is passed the user's input, and returns the new value to use as the input.

    您可以使用此函数保存输入,并将其原封不动地传递给验证。如果您只想在输入不正确的情况下存储输入,则需要在此函数中再次检查条件

    例如:

    import pyinputplus as p
    import re
    
    # hardcoded values for example
    incorrectAnswers = []
    questionNumber = 1
    num1 = 2
    num2 = 3
    prompt = f'#{questionNumber}: {num1} x {num2} = '
    
    def checkAndSaveInput(n):
        if not (re.match(f'^{num1 * num2}$',n)):
            incorrectAnswers.append(n)
        return(n)
    
    inp = p.inputStr(prompt,
        allowRegexes=[f'^{num1 * num2}$'],
        blockRegexes=[('.*','Incorrect!')],
        applyFunc=checkAndSaveInput)
    
    print("Your wrong answers were:")
    for a in incorrectAnswers:
        print(f'  {a}')
    

    执行:

    #1: 2 x 3 = six
    Incorrect!
    #1: 2 x 3 = 4
    Incorrect!
    #1: 2 x 3 = 5
    Incorrect!
    #1: 2 x 3 = 6
    Your wrong answers were:
      six
      4
      5
    
  2. 由于使用上述方法,您仍然需要再次检查条件,因此也可以直接编写custom ^{} function。下面的示例仅使用allowRegexesblockRegexes中的正则表达式来验证是否输入了int,并且实际的结果检查不是使用正则表达式而是使用简单的数学进行的。与上述方法不同的是,值实际上只在之后传递给检查函数,确保它们与^{中的模式匹配

    import pyinputplus as p
    
    # hardcoded values for example
    incorrectAnswers = []
    questionNumber = 1
    num1 = 2
    num2 = 3
    prompt = f'#{questionNumber}: {num1} x {num2} = '
    
    def checkAndSaveInput(n):
        if((num1 * num2) != int(n)):
            incorrectAnswers.append(n)
            raise Exception('Incorrect.')
        else:
            print('Correct!')
    
    inp = p.inputCustom(checkAndSaveInput,
        prompt=prompt,
        allowRegexes=[r'^\d+$'],
        blockRegexes=[('.*','Please enter a valid number!')])
    
    print("Your wrong answers were:")
    for a in incorrectAnswers:
        print(f'  {a}')
    

    执行:

    #1: 2 x 3 = six
    Please enter a valid number!
    #1: 2 x 3 = 4
    Incorrect.
    #1: 2 x 3 = 5
    Incorrect.
    #1: 2 x 3 = 6
    Correct!
    Your wrong answers were:
      4
      5
    

相关问题 更多 >