使用搁置模块的Python Madlibs项目自动化无聊的东西

时间:2017-11-26 03:48:27

标签: python-3.x

我一直在学习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()

有人可以向我解释搁置模块如何提高效率吗?谢谢!

14 个答案:

答案 0 :(得分:1)

这是我想出的。

#include <iostream>
#include <sstream>

#include <cpr/cpr.h>
#include <elmo.hpp>

void appInit(char *args) {

}

int main(int argc, char *argv) {

if (argc > 1) {
    appInit(argv);
} else {
    std::cout << "Usage: a.out [search keyword]" << std::endl;
}

int limit = 3;

cpr::Parameters parameters{{"query", input},
                    {"limit", "3"},
                    {"indent", "true"},
                    {"key", "AIzaSyA5Xr82w7LrJgaLPb99P4kVZzFlxYuPhng"}};

auto response = cpr::Get(cpr::Url{
    "https://kgsearch.googleapis.com/v1/entities:search"}, parameters);

auto elmo = nlohmann::elmo::parse(response.text);
elmo.flatten();

for (int i=0; i<limit; i++) {
    std::ostringstream oss;
    std::cout << elmo["/itemListElement/0/result/name"_elmo_pointer];
    //std::cout << elmo["/itemListElement/i/result/@type/0"_elmo_pointer] << std::endl;
    //std::cout << elmo["/itemListElement/i/result/@type/1"_elmo_pointer] << std::endl;
    std::cout << elmo["/itemListElement/0/result/description"_elmo_pointer] << std::endl;
    std::cout << elmo["/itemListElement/0/result/detailedDescription/articleBody"_elmo_pointer] << std::endl;
    std::cout << elmo["/itemListElement/0/result/image/url"_elmo_pointer] << std::endl;
}

//std::cout << json.dump(4) << std::endl;
}

答案 1 :(得分:1)

#! python3
import re
import pyinputplus as pyip

def quest(x):
    t = re.compile(r'(adjective|noun|adverb|verb)?', re.I)
    p = t.findall(x)                                         #<-Pick out all the 'adjective|noun|adverb|verb' 

    for k in list(p): 
        if k.lower() == 'adjective':
           print('Enter an adjective: ')
           adj = pyip.inputStr(blockRegexes =[r'adjective']) #<-Blocks the user from typing the word 'adjective' as a reply.
           a = re.compile(r'(adjective)', re.I)              #<-This regex will be used to substitute all matched phrases.
           x = a.sub(f'{adj}',x,1)                           #<-Replacing the matched phrases with user's input, using 'a.sub()'.
        elif k.lower() == 'noun':
           print('Enter a noun: ')
           nou = pyip.inputStr(blockRegexes =[r'noun'])
           a = re.compile(r'(noun)', re.I)
           x = a.sub(f'{nou}',x,1)
        elif k.lower() == 'adverb':
           print('Enter an adverb: ')
           adv = pyip.inputStr(blockRegexes =[r'adverb'])
           a = re.compile(r'(adverb)', re.I)
           x = a.sub(f'{adv}',x,1)
        elif k.lower() == 'verb':
           print('Enter a verb: ')
           ver = pyip.inputStr(blockRegexes =[r'verb'])
           a = re.compile(r'(verb)', re.I)
           x = a.sub(f'{ver}',x,1)

    print(x)

s = input('Enter a sentence: ')                             #<-The input text could be from anywhere, e.g. reading from a file, etc.

quest(s)

答案 2 :(得分:1)

import re

# Open text file and save string to variable.
file_name = input("Enter the full name of the text file: ")
text_file = open(file_name, "r")
text = text_file.read()
text_file.close
# Create regex to find ADJECTIVE, NOUN, ADVERB, or VERB.
mad_libs_regex = re.compile(r"(ADJECTIVE|NOUN|ADVERB|VERB)")
# For each match, prompt user for word and update string.
while mad_libs_regex.search(text) != None:
    word = input(f"Enter a(n) {mad_libs_regex.search(text).group().lower()}: ")
    text = mad_libs_regex.sub(word, text, 1)
# Save updated string to new text file.
mad_libs_file = open(f"{file_name.split('.')[0]}_madlibs.txt", "w")
mad_libs_file.write(text)
mad_libs_file.close
# Print updated string.
print(text)

答案 3 :(得分:0)

我没有搁置,但仍然比你的效率更高。

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)

编码的好处在于有多种正确的方法可以做。我相信它可以用于搁置,但你不需要它(它可能实际上使事情过于复杂)。

答案 4 :(得分:0)

  

唯一的问题是我确信我想要使用搁架模块,但我仍然不确定它是如何工作的。

不,这不是强制性的。但是,它对于前一个问题是强制性的。对于此问题,您必须使用文件,因为您还在同一章节中学习了文件。

无论如何,这是我的代码:

#!/usr/bin/python

import re

file = open('madlibs')
text = file.read()
file.close()

regex = re.compile(r'(ADJECTIVE)|(NOUN)|(VERB)')

for i in regex.findall(text):
    for j in i:
        if j != '':
            reg = re.compile(r'{}'.format(j))
            inp_text = input('Enter the substitute for %s: ' %j)
            text = reg.sub(inp_text, text, 1)

print(text)

file = open('madlibs_ans', 'w')
file.write(text)
file.close()

对我来说,这看起来更简单。 :)

答案 5 :(得分:0)

架子模块不适合这样做,原始的madlib和填充的madlib都将是普通的纯文本字符串,.txt文件可以很好地工作,并允许用户更轻松地编辑和阅读madlib文件无需深入研究您的代码。但是我确实在这里看到了两行代码,效率很低。

替换:

using (NetworkStream networkStream = client.GetStream())
using (StreamWriter streamWriter = new StreamWriter(networkStream))
using (StreamReader streamReader = new StreamReader(networkStream))
{
    await streamWriter.WriteLineAsync(data);
    await streamWriter.FlushAsync();

     do
     {
         await streamReader.ReadLineAsync();
     } while (networkStream.DataAvailable);

     networkStream.Close();
}

使用:

newmadlibslist = list(basemadlibs.read())
newtext = ''.join(newmadlibslist)

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

答案 6 :(得分:0)

这是我的解决方案。我也没有搁置。

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

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

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()

答案 7 :(得分:0)

这是我的解决方案。几周前,我开始阅读这本书。任何提示将不胜感激。

#! /Users/santiagofacchini/.pyenv/shims/python

import re

path = '/Users/santiagofacchini/Desktop/text.txt'
input_file = open(path, 'r')
file_string = input_file.read()

file_string = re.sub(r'ADJECTIVE', input('Enter an adjective:\n'), file_string)
file_string = re.sub(r'NOUN', input('Enter a noun:\n'), file_string)
file_string = re.sub(r'ADVERB', input('Enter an adverb:\n'), file_string)
file_string = re.sub(r'VERB', input('Enter a verb:\n'), file_string)

output_file = open('/Users/santiagofacchini/Desktop/text_output.txt', 'w')
output_file.write(file_string)
print(file_string)

答案 8 :(得分:0)

没有使用Shelve模块,但我只是想使用到目前为止从书中学到的其他东西来分享自己略有不同的解决方案。

#! python3

#   Usage: python3 madlibsScript.py inputTextFile.txt

import os, re, sys

# change current working directory to directory of input file.
os.chdir(os.path.dirname(sys.argv[1]))

# open text file and save content to python variable
inputTextFile = open(sys.argv[1], 'r')
textFileContent = inputTextFile.read()
inputTextFile.close()

# regex object for placeholders
wordCheck = re.compile(r'VERB|NOUN|ADJECTIVE|ADVERB')

# check content for placeholders and get input from user for substitution
while wordCheck.search(textFileContent).group() in textFileContent:
    userInput = input('Enter your {}:   '.format(wordCheck.search(textFileContent).group().lower()))

    # substitute placeholder for the user input.
    textFileContent = wordCheck.sub(userInput, textFileContent, 1)

    # break from loop if there are no more placeholders
    if wordCheck.search(textFileContent) == None:
        break

# print to screen and save to file
print(textFileContent)

outputTextFile = open('madlibs-output.txt', 'w')
outputTextFile.write(textFileContent)
outputTextFile.close()

答案 9 :(得分:0)

对于只有2个句子的示例游戏,搁置会延长代码太多。 但是Shelve模块可以用于在实时项目中最大程度地扩展游戏。

以下代码使用关键字,例如形容词,名词等。并分别保存数据。 然后请求用户输入并替换游戏内容中的每个关键字。

使用货架代码

import re, shelve

def madlib(datapath, filepath):
    newShelf=shelve.open(datapath)
    userkeys=[]  
    newShelf["keywords"]=userkeys
    while True:
        userinput = input("Enter madlib rule keyword: ")
        if userinput=="":
            break
        else:
            userkeys.append(userinput)
            print("Press return key to save and exit.")
    newShelf["keywords"]=userkeys
    print(newShelf["keywords"])
    newShelf.close()
    
    madlib_file=open(filepath)
    game_content=madlib_file.read()
    madlib_file.close()
    print("\n\nGame content:\n"+game_content)
    
    datafile=shelve.open(datapath)
    match_data="|".join(datafile["keywords"])
    while True:
        mRegex=re.compile(match_data, re.I)
        match=mRegex.search(game_content)
        if match==None:
            break
        else:
            if match.group().startswith(("A","a")):  #for other vowels need to specify
                newWord=input(f"Enter an {match.group().lower()}: ")
            else:
                newWord=input(f"Enter a {match.group().lower()}: ")            
            game_content=mRegex.sub(newWord,game_content, count=1)
    datafile.close()
    print("\nOutput:\n"+game_content)
    file2=open(filepath,"w")
    file2.write(game_content)
    file2.close()
    
madlib("madlibData","madlibgamecontent.txt")

答案 10 :(得分:0)

在上一个练习中,我们使用了shelve模块,因为我们需要像文件这样的字典,但是在这里我们不需要(我们没有键,只有纯文本。)所以没有理由使用它。您认为您的代码是正确,尽管很长。我在这里共享我的版本(我选择不将其存储在文件末尾)

import re
file_sentence = open('madLib.txt','r')
type_regex = re.compile(r'(ADJECTIVE|NOUN|ADVERB|VERB)',re.IGNORECASE)

for line in file_sentence.readlines():
    while type_regex.search(line):
        toChange = type_regex.search(line)
        ans = input('Please input a/an '+toChange.group())
        line = type_regex.sub(ans,line,1)
    print(line)
#then u can create a file and write on it.

答案 11 :(得分:0)

import re
madlibFile = open('W:\\User\\textfiles\\madLib.txt')
text = madlibFile.read()
madlibFile.close()
check = re.compile(r'ADJECTIVE|NOUN|VERB|ADVERB')

while True:
    result = check.search(text)
    if result == None:
        break
    elif 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()
    text = check.sub(i,text,1)

print(text)

答案 12 :(得分:0)

到目前为止我是这样解决的 导入重新

fileName = input('what file to modify: ')
with open(fileName, 'r') as file:
    fileContent = file.read()

adjective = input('AJECTIVE = ')
noun = input('NOUN = ')
verb = input('VERB = ')

fileContent = fileContent.replace('ADJECTIVE', adjective)
fileContent = fileContent.replace('NOUN', noun)
fileContent = fileContent.replace('VERB', verb)

with open(fileName, 'w') as file:
    file.write(fileContent)

答案 13 :(得分:0)

我的版本更简单,易于阅读。对于 vimlovers。

1 import re                                                                                                                  |  /home/kali/                  
2                                                                                                                            |  ▸   books/                  
3 file = open('sample.txt')                                                                                                  |  ▸   Desktop/                
4 content = file.readlines()                                                                                                 |  ▸   Documents/              
5 content = ' '.join(content)                                                                                                |  ▸   Downloads/              
6 word_regex = re.compile(r'(ADJECTIVE|VERB|NOUN)',re.IGNORECASE)                                                            |  ▸   Music/                  
7                                                                                                                            |  ▸   Pictures/               
8 print(content)                                                                                                             |  ▸   programming/            
9  words = word_regex.findall(content)                                                                                        |  ▸   Public/                                                                                                                                             |  ▸   Templates/              
11 print(words)                                                                                                               |  ▸   Videos/                 
12 for i in words:                                                                                                            |~                              
13                                                                                                                            |~                              
14 content = word_regex.sub(input(f"Enter an {i}?"),content,1)                                                            |~                              
15 file.close()                                                                                                               |~                              
16 file2 = open('output.txt','w')                                                                                             |~                              
17 file2.write(content)                                                                                                       |~                              
18 file2.close()                                                                                                              |~                              

~