【问题标题】:How can can I get the entered value that matches blockRegexes in PyInputPlus.inputStr() function如何在 PyInputPlus.inputStr() 函数中获取与 blockRegexes 匹配的输入值
【发布时间】:2020-08-08 05:14:35
【问题描述】:

我有一个来自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}')

【问题讨论】:

    标签: python python-3.x regex validation input


    【解决方案1】:

    实际上有不同的方法可以实现你想要的。

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

      applyFunc (Callable, None):一个可选函数,用于传递用户的输入,并返回新值以用作输入。

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

      例子:

      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 inputCustom() function。以下示例使用allowRegexesblockRegexes 中的正则表达式仅验证输入了int,并且实际结果检查不是使用正则表达式而是通过简单的数学来完成的。与上述方法的不同之处在于,这些值实际上只在确保它们与allowRegexes 中的模式匹配之后才交给检查函数。

      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
      

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-01-02
      相关资源
      最近更新 更多