填空小测验应用

# A list of replacement words to be passed in to the play game function. 
parts_of_speech1  = ["PLACE", "PERSON", "PLURALNOUN", "NOUN", "NAME", "VERB", "OCCUPATION", "ADJECTIVE"]

# The following are some test strings to pass in to the play_game function.
test_string1 = "Hi, my name is NAME and I really like to VERB PLURALNOUN. I'm also a OCCUPATION at PLACE."
test_string2 = """PERSON! What is PERSON going to do with all these ADJECTIVE PLURALNOUN? Only a registered 
OCCUPATION could VERB them."""
test_string3 = "What a ADJECTIVE day! I can VERB the day off from being a OCCUPATION and go VERB at PLACE."

# Checks if a word in parts_of_speech is a substring of the word passed in.
def word_in_pos(word, parts_of_speech):
    for pos in parts_of_speech:
        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 play_game(ml_string, parts_of_speech):    
    replaced = []
    ml_string = ml_string.split()
    for word in ml_string:
        replacement = word_in_pos(word, parts_of_speech)
        if replacement != None:
            user_input = raw_input("Type in a: " + replacement + " ")
            word = word.replace(replacement, user_input)
            replaced.append(word)
        else:
            replaced.append(word)
    replaced = " ".join(replaced)
    return replaced
    
print play_game(test_string1, parts_of_speech1)   

自己运行代码

代码下载:http://cn-static.udacity.com/mlnd/madlibs_generator.py

现在已经创建好了可运行的小测验应用,我们运行下代码,看看效果如何!从之前的部分下载 madlibs_generator.py 后,打开命令行界面(如果你使用的是 Mac 或 Linux 计算机,则打开终端;如果使用的是 Windows 计算机,则打开 Git Bash)。

注意:文件可能不会立即下载,而是在新的浏览器标签页中打开。如果是这样,你可以将代码复制粘贴到在文本编辑器中新建的文件中,名称设为 madlibs_generator.py。将文件保存到易于访问的地方,例如桌面。

首先通过 cd 命令转到 madlibs_generator.py 的保存目录下。如果你刚刚下载了文件,并且未将文件移到别的地方,则可能位于 Downloads 文件夹或桌面上。

输入命令 python madlibs_generator.py(如果你是在 Windows 设备上使用 Git Bash,则输入命令 winpty python madlibs_generator.py)。应用应该开始运行了,你可以将你的答案直接输入命令行窗口中!

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值