首页
学习
活动
专区
工具
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

回答 12

Stack Overflow用户

发布于 2017-11-30 18:28:02

我没有架子,但仍然比你的效率高得多。

代码语言:javascript
复制
import re

#Open the Madlibs File
madLibs = open("..\\MadLibs.txt")
#Save the contents so you can modify it
content = madLibs.read()
madLibs.close()
check = re.compile(r'ADJECTIVE|NOUN|VERB|ADVERB')
#Loop to check for the words to replace
while True:
    result = check.search(content)
#end the Loop if there is nothing left to replace
    if result == None:
        break

#Get user input as soon as one is found (this if statement is just for
#grammatical correctness, and could probably be done better
    if result.group() == "ADJECTIVE" or result.group() == "ADVERB":
        print("Enter an %s:" % (result.group().lower()))
    elif result.group() == "NOUN" or result.group() == "VERB":
        print("Enter a %s:" % (result.group().lower()))
    i = input()
#substitute the word as soon as you come across it
#then Python only needs to search for one word at once, and automatically
#knows when it's done
    content = check.sub(i, content, 1)
print(content)
#Choose how to name the file you save and then save the file
print("Name your file:")
name = input()
newFile = open("..\\%s.txt" % (name), "w")
newFile.write(content)

编码的好处是有多种正确的方法来做事情。我确信它可以和shelve一起工作,但是你不需要它(而且它可能会使事情变得过于复杂)。

票数 3
EN

Stack Overflow用户

发布于 2018-08-06 03:31:52

工具架模块不适合这样做,原始的madlib和填充的madlib都将是一个普通的纯文本字符串,.txt文件工作得很好,允许用户更容易地编辑和阅读madlib文件,而不需要深入研究您的代码。然而,我确实在这里看到了效率非常低的两行代码。

替换:

代码语言:javascript
复制
newmadlibslist = list(basemadlibs.read())
newtext = ''.join(newmadlibslist)

通过以下方式:

代码语言:javascript
复制
newtext = basemadlibs.read()

basemadlibs.read()已经返回了一个字符串,没有理由从中提取一个列表

票数 1
EN

Stack Overflow用户

发布于 2019-05-02 16:01:45

这是我的解决方案。我也没有使用shelve。

注意:re.findall是一种非常有用的解析词性的方法。它可以识别旁边有标点符号的词类。例如ADJECTIVE,NOUN!—ADVERB

注意:在我的解决方案中,madlibsoriginal.txt文件中的所有词性都必须为大写。

代码语言:javascript
复制
import os, re

#Get original madlib text from the file
ORIG_FILE_MADLIB = open('/Users/mac/python/madlibs/madlibsoriginal.txt', 'r')
ORIG_MADLIB = ORIG_FILE_MADLIB.read()
ORIG_FILE_MADLIB.close()

#Parse the original madlib text into a list
split_madlib = re.findall(r"[\w']+|[.,!?;]|\s", ORIG_MADLIB)

#Declare list of parts of speech to (later) search for and replace
PARTS_OF_SPEECH = ['ADJECTIVE', 'NOUN', 'ADVERB', 'VERB']

#Search for parts of speech
for i in range(len(split_madlib)): #Tip: "For each word in the text"
    for j in range(len(PARTS_OF_SPEECH)): #Tip: "For each part of speech"
        if split_madlib[i] == PARTS_OF_SPEECH[j]: #Tip: "If the word is a part of speech"
            #Prompt for a replacement word
            new_word = input('Enter a ' + PARTS_OF_SPEECH[j].lower() + ': ')
            split_madlib[i] = new_word

#Create file with the new madlib text
NEW_FILE_MADLIB = open('/Users/mac/python/madlibs/madlibsnew.txt', 'w')
NEW_FILE_MADLIB.write(''.join(split_madlib))
NEW_FILE_MADLIB.close()
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/47492847

复制
相关文章

相似问题

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