使用Python在“填空”程序中验证用户输入

时间:2016-01-04 17:49:10

标签: python python-2.7 validation

作为编程的新手,我目前正在参加考试,我应该为madlibs游戏提交Python代码。我目前在代码中缺少的是用户输入验证应该出现在文本中的单词。

现在该程序能够获取用户输入并显示全文,但我不知道在我的代码中将用户输入的验证放在何处,特别是因为我正在查看不同单词的列表。我知道我必须在某处定义变量来检查用户输入,但我现在完全陷入困境。

这是我的代码的当前工作版本,即没有尝试对单词进行输入验证。

print "Welcome to my first quiz with user input"
print "Lets get cracking straight away"
print
import time
while True:
    difficulty_level = raw_input("Which difficulty level would you like? Type EASY, MEDIUM or HARD to continue?  ")
    if difficulty_level.upper() == "EASY":
        time.sleep(1)
        print "Here it goes..."
        print
        time.sleep(1)
        print "Here's your text. Should be an easy one. Just fill in the blanks for _Word_ 1-3."
        print
        print
        print "Python is a _Word1_ language that provides constructs intended to enable clear programs on both small and large scale. Python implementation was started in December _Word2_ by Guido von Rossum. The most simple _Word3_ in Python is _Word4_ and normally used at the beginning to tell Python to write 'Hello World' on the screen."
        print
        # A list of replacement words to be passed in to the play game function. 
        parts_of_speech1  = ["_Word1_", "_Word2_", "_Word3_", "_Word4_"]
        # The following is the text for the easy text..
        easy_text = "Python is a _Word1_ language that provides constructs intended to enable clear programs on both small and large scale. Python implementation was started in December _Word2_ by Guido von Rossum. The most simple _Word3_ in Python is _Word4_ and normally used at the beginning to tell Python to write 'Hello World' on the screen."
        # Checks if a word in parts_of_speech is a substring of the word passed in.
        def word_in_pos_easy(word, parts_of_speech1):
            for pos in parts_of_speech1:
                if pos in word:
                    return pos
            return None 
        # Plays a full game of mad_libs. A player is prompted to replace words in the easy text, 
        # which appear in parts_of_speech with their own words.  
        def easy_game(easy_text, parts_of_speech1):    
            replaced = []
            easy_text = easy_text.split()
            for word in easy_text:
                replacement = word_in_pos_easy(word, parts_of_speech1)
                if replacement != None:
                    user_input = raw_input("Type in: " + replacement + " ")
                    word = word.replace(replacement, user_input)
                    replaced.append(word)
                else:
                    replaced.append(word)
            replaced = " ".join(replaced)
            print
            time.sleep(1)
            print "Ok, lets see your results. Does it make sense?"
            print
            time.sleep(1)
            return replaced
            print  
            time.sleep(1) 
        print easy_game(easy_text, parts_of_speech1)
    # Difficulty Level Medium
    if difficulty_level.upper() == "MEDIUM":
        time.sleep(1)
        print "Good choice. Lets see how much you know about Python"
        print
        time.sleep(1)
        print "Here's your text. It's a tricky one that requires some more knowledge about Python. Just fill in the blanks for _Word_ 1-3."
        print
        print
        print "A string object is _Word1_, i.e. it cannot be modified after it has been created. An important concept in Python and other programming languages is _Word2_. You use them to store a value. To assign a value to a Variable you use the _Word3_ operator. A more versatile data type in Python is _Word4_. They contain items separated by commas and within square brackets. To some extent they are similar to arrays in C."
        print
        # A list of replacement words to be passed in to the play game function. 
        parts_of_speech2  = ["_Word1_", "_Word2_", "_Word3_", "_Word4_"]

        # The following are some test strings to pass in to the play_game function.
        medium_text = "A string object is _Word1_, i.e. it cannot be modified after it has been created. An important concept in Python and other programming languages is _Word2_. You use them to store a value. To assign a value to a Variable you use the _Word3_ operator. A more versatile data type in Python is _Word4_. They contain items separated by commas and within square brackets. To some extent they are similar to arrays in C."
        # Checks if a word in parts_of_speech is a substring of the word passed in.
        def word_in_pos_medium(word, parts_of_speech2):
            for pos in parts_of_speech2:
                if pos in word:
                    return pos
            return None
        # Plays a full game of mad_libs. A player is prompted to replace words in ml_string, 
        # which appear in parts_of_speech with their own words.  
        def medium_game(medium_text, parts_of_speech2):    
            replaced = []
            medium_text = medium_text.split()
            for word in medium_text:
                replacement = word_in_pos_medium(word, parts_of_speech2)
                if replacement != None:
                    user_input = raw_input("Type in: " + replacement + " ")
                    word = word.replace(replacement, user_input)
                    replaced.append(word)
                else:
                    replaced.append(word)
            replaced = " ".join(replaced)
            print
            time.sleep(1)
            print "OK, lets see your results. Does it make sense?"
            print
            time.sleep(1)
            return replaced
            print
            time.sleep(1) 
        print medium_game(medium_text, parts_of_speech2)
    # Difficulty Level Hard
    if difficulty_level.upper() == "HARD":
        time.sleep(1)
        print "Bold move! Here we go. Check out this text. It's a tough one"
        print
        time.sleep(1)
        print "Here's your text. This one requires quite some Python knowledge"
        print
        print
        print "Similar to other programming languages, Python has flow controls. The most known statement is the _Word1_ statement. It can be combined with an else statement and helps to process a logic based on a specific condition. For more repetitive processing one needs to use loops. _Word2_ loops execute a sequence of statements multiple times and abbreviates the code that manages the loop variable._Word3_ loops repeat a statement or group of statements while a given condition is TRUE. It tests the condition before executing the loop body."
        print
        # A list of replacement words to be passed in to the play game function. 
        parts_of_speech3  = ["_Word1_", "_Word2_", "_Word3_", "_Word4_"]
        # The following are some test strings to pass in to the play_game function.
        hard_text = "Similar to other programming languages, Python has flow controls. The most known statement is the _Word1_ statement. It can be combined with an else statement and helps to process a logic based on a specific condition. For more repetitive processing one needs to use loops. _Word2_ loops execute a sequence of statements multiple times and abbreviates the code that manages the loop variable. _Word3_ loops repeat a statement or group of statements while a given condition is TRUE. It tests the _Word4_ before executing the loop body."
        # Checks if a word in parts_of_speech is a substring of the word passed in.
        def word_in_pos_hard(word, parts_of_speech3):
            for pos in parts_of_speech3:
                if pos in word:
                    return pos
            return None      
        # Plays a full game of mad_libs. A player is prompted to replace words in the hard text,
        # which appear in parts_of_speech with their own words.
        def hard_game(hard_text, parts_of_speech3):    
            replaced = []
            hard_text = hard_text.split()
            for word in hard_text:
                replacement = word_in_pos_hard(word, parts_of_speech3)
                if replacement != None:
                    user_input = raw_input("Type in: " + replacement + " ")
                    word = word.replace(replacement, user_input)
                    replaced.append(word)
                else:
                    replaced.append(word)
            replaced = " ".join(replaced)
            print
            time.sleep(1)
            print "OK, lets see your results. Does it make sense?"
            print
            time.sleep(1)
            return replaced
            print
        print hard_game(hard_text, parts_of_speech3)
    else: 
        print "Sorry, that was not a correct input. Please enter EASY, MEDIUM or HARD to set the difficulty level."

1 个答案:

答案 0 :(得分:0)

我将如何做到这一点:

from random import shuffle
import sys
from time import sleep

# version compatibility shim
if sys.hexversion <= 0x3000000:  # Python 2.x
    inp = raw_input
else:                            # Python 3.x
    inp = input

def get_word(prompt):
    return inp(prompt).strip().lower()

def shuffled(words):
    words_copy = list(words)
    shuffle(words_copy)
    return words_copy

class MadLib:
    BLANK = "___"
    DELAY = 1

    def __init__(self, intros, prompt, words):
        self.intros = intros
        self.prompt = prompt
        self.words = words
        self.num_words = len(words)
        assert prompt.count(self.BLANK) == self.num_words, "Number of blanks must match number of words!"

    def play(self):
        # show introduction
        for s in self.intros:
            sleep(self.DELAY)
            print(s, flush=True)
        # display madlib with blanks
        sleep(self.DELAY)
        print(self.prompt)
        # get words from user
        print("Words available: " + ", ".join(shuffled(self.words)))
        gotten = [
            get_word("Word {}: ".format(i))
            for i in range(1, self.num_words + 1)
        ]
        # evaluate results
        num_right = sum(g == w for g,w in zip(gotten, self.words))
        if num_right == self.num_words:
            print("You did it!")
            return True
        else:
            print("You got {} out of {} words right.".format(num_right, self.num_words))
            return False

madlibs = {
    "easy":
        MadLib(
            [
                "Here we go...",
                "Here's your text. Should be an easy one.",
                "Just fill in the blanks!"
            ],
            (
                "Python is a ___ language that provides constructs intended to "
                "enable clear programs on both small and large scale. "
                "Python implementation was started in December ___ by "
                "Guido von Rossum. The most basic ___ in Python is ___, "
                "often used by beginners to tell Python to display 'Hello "
                "World' on the screen."
            ),
            ['programming', '1989', 'command', 'print']
        ),
    "medium":
        MadLib(
            [
                "Good choice. Lets see how much you know about Python",
                "Here's your text. It's a tricky one that requires some more knowledge about Python.",
                "Just fill in the blanks!"
            ],
            (
                "A string object is ___, i.e. it cannot be modified after it "
                "has been created. An important concept in Python and other "
                "programming languages is the ___, used to store a value. "
                "To assign a value to you use the ___ operator. A more "
                "versatile data type in Python is ___, containing items "
                "separated by commas and within square brackets and to "
                "some extent they are similar to arrays in C."
            ),
            ['immutable', 'variable', 'equals', 'list']
        ),
    "hard":
        MadLib(
            [
                "Bold move! Here we go. Check out this text. It's a tough one!",
                "Here's your text.  This one requires quite some Python knowledge.",
                "Just fill in the blanks!",                
                "Here's your text:"
            ],
            (
                "Similar to other programming languages, Python has flow "
                "control commands. The most common is ___ which lets you branch "
                "based on a condition. Looping commands like ___ execute "
                "statements a given number of times, or ___ repeats statements "
                "so long as a condition is True."
            ),
            ['if', 'for', 'while']
        )
}    

def main():
    print(
        "Welcome to my first quiz with user input!\n"
        "Lets get cracking straight away."
    )
    while True:
        choice = get_word("Which difficulty level would you like? [easy, medium, hard] (or just hit Enter to exit) ")
        if not choice:
            break
        elif choice in madlibs:
            madlibs[choice].play()
        else:
            print("Sorry, that was not a recognized option.")

if __name__=="__main__":
    main()