import re
text="""Giraffes have aroused
the curiosity of __PLURAL_NOUN__
since earliest times. The
giraffe is the tallest of all
living __PLURAL_NOUN__, but
scientists are unable to
explain how it got its long
__PART_OF_THE_BODY__. The
giraffe's tremendous height,
which might reach __NUMBER__
__PLURAL_NOUN__, comes from
it legs and __BODYPART__.
"""
def mad_libs(mls):
"""
:param mls: 字符串
双下划线部分的内容要由玩家来补充。
双下划线不能出现在提示语中,如不能
出现 __hint_hint__,只能是 __hint__。
"""
hints=re.findall("__.*?__", mls)
if hints is not None:
for word in hints:
q="Enter a {}".format(word)
new=input(q)
mls=mls.replace(word, new, 1)
print("\n")
mls=mls.replace("\n", "")
print(mls)
else:
print("invalid mls")
mad_libs(text)
书上的程序,执行时只在控制台输出了:
Enter a __PLURAL_NOUN__
接下来怎么操作?
书上说,使用re.findall匹配变量text中所有被双下划线包围的内容(每个均为玩家需要输入答案进行替代的内容),以列表形式返回。然后,对列表中的元素进行循环,通过每个提示来要求玩家提供一个新的单词。之后,创建一个新的字符串,将提示替换为玩家输入的词。循环结束后,打印替换完成后的新字符串。
--
FROM 118.197.220.*