首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >使用带搁置模块的Python Madlibs项目实现枯燥的自动化

使用带搁置模块的Python Madlibs项目实现枯燥的自动化
EN

Stack Overflow用户
提问于 2017-11-26 11:48:27
回答 12查看 4.4K关注 0票数 1

随着《用python自动化枯燥的东西》这本书,我一直在学习Python作为我的第一种编码语言,在关于读/写文件和使用搁置模块的章节之后,我设法创建了madlibs程序。唯一的问题是,我确定我应该使用搁置模块,但我仍然不确定它是如何工作的。代码如下:

代码语言:javascript
复制
import re

basemadlibs = open('C:\\Users\\Username\\Desktop\\MADLIBS.txt', 'r')
#creates a string out of the contents of the madlibs file
newmadlibslist = list(basemadlibs.read())
newtext = ''.join(newmadlibslist)
#regex for finding placeholders(VERB, ADJECTIVE, ect.) in the  madlibs file content
placeholders = re.compile(r'[A-Z]{2,10}')
#replaces the placeholders with a %s
emptytext = placeholders.sub('%s', newtext)
#creates a list of inputs to substitute the %s in the emptystring
replacements = []
for i in range(len(placeholders.findall(newtext))):
    print('type a\\an: ' + placeholders.findall(newtext)[i])
    replacement = input()
    replacements.append(replacement)
#string formats the %s placeholders with the replacements
madlibcompleted = emptytext % tuple(replacements)
#prints the completed mad lib
print(madlibcompleted)
#saves a copy of the completed madlib to the desktop called 'alterdMADLIBS.txt'
alteredmadlibs = open('C:\\users\\Username\\Desktop\\alteredMADLIBS.txt', 'w')
alteredmadlibs.write(madlibcompleted)
alteredmadlibs.close()
basemadlibs.close()

有人能给我解释一下搁置模块是如何提高效率的吗?谢谢!

EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/47492847

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档