python 疯狂填词 mad libs

来源:转载

import osimport re# 读取文本文件file = open(r'F:/workspace/python/text/madlib.txt')strs = file.read()#sub函数不改变原字符串adjective = input("Enter a adjective:")adjective_regex = re.compile('ADJECTIVE')strs = adjective_regex.sub(adjective, strs)noun = input("Enter a noun:")noun_regex = re.compile('NOUN')strs = noun_regex.sub(noun, strs)verb = input("Enter a verb:")verb_regex = re.compile('VERB')strs = verb_regex.sub(verb, strs)noun = input("Enter a noun:")noun_regex = re.compile('NOUN')strs = noun_regex.sub(noun, strs)print(strs)# 写入改动后的文件fileObj = open(r'F:/workspace/python/text/madlib_change.txt', 'w')fileObj.write(strs)fileObj.close()

madlib.txt内容:The ADJECTIVE panda walked to the NOUN and then VERB. A nearby NOUN was unaffected by these events

分享给朋友:
您可能感兴趣的文章:
随机阅读: