随着《用python自动化枯燥的东西》这本书,我一直在学习Python作为我的第一种编码语言,在关于读/写文件和使用搁置模块的章节之后,我设法创建了madlibs程序。唯一的问题是,我确定我应该使用搁置模块,但我仍然不确定它是如何工作的。代码如下:
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()
有人能给我解释一下搁置模块是如何提高效率的吗?谢谢!
https://stackoverflow.com/questions/47492847
复制相似问题