使用Python的Mad Lib程序

时间:2016-04-21 20:57:08

标签: python

使用Python自动化无聊的东西在第8章中有一个项目: 创建一个Mad Libs程序,该程序读入文本文件,并允许用户在文本文件中出现单词ADJECTIVE,NOUN,ADVERB或VERB的任何地方添加自己的文本。

需要创建新的文本文件并将结果打印到屏幕上。

我的解决方案导致创建一个空白的新文件,并在终端中不显示任何内容。我在OS X上使用Python 3.5.1。

#! /usr/bin/env python3


with open("/Users/Maverick/madLibProject1.txt", "wt") as fout:
    with open("/Users/Maverick/madLibProject.txt", "r") as fin:
        for line in fin:
            if line == "ADJECTIVE":
                adj == input('Enter an adjective:\n')
                fout.write(line.replace('ADJECTIVE', adj))
            elif line == "NOUN":
                nou == input('Enter a noun:\n')
                fout.write(line.replace('NOUN', nou))
            elif line == "ADVERB":
                adv = input('Enter an adverb:\n')
                fout.write(line.replace('ADVERB', adv))
            elif line == "VERB":
                ver = input('Enter a verb:\n')
                fout.write(line.replace('VERB', ver))

fname = "/Users/Maverick/madLibProject1.txt"
project = open(fname, 'r')
data = project.read()
print(data)

3 个答案:

答案 0 :(得分:0)

看看这段代码:

data = "a ADJECTIVE NOUN VERB ADVERB to the NOUN to VERB some NOUN"
for part_of_speech in ["ADJECTIVE", "NOUN", "ADVERB", "VERB"]:
    while data.find(part_of_speech) > -1:
        data = data.replace(part_of_speech, input("enter a %s: " % (part_of_speech.lower())), 1)

print(data)

有些事情可以帮助你理解这个例子:

还可以尝试在for循环下添加print(line)以更好地了解您的计划。正如其他人所说,调试技巧是你在编写程序时学到的最重要的事情之一。

答案 1 :(得分:0)

作为一个新的python程序员,我把一切都变得如此简单。我得到了一个名为“ source.txt”的文件,并在其中写入: “大熊猫走到了名词,然后是动词。附近的名词不受这些事件的影响。” 对于待办事项列表,1.首先打开文件,获取内容。 2.接受用户的输入。 3.Re.sub。(我认为作者希望我们使用Re.sub。) 4.将新内容写入新文件。 这是我的代码,希望对您有所帮助。

import re
textfile = open("source.txt")
textcontent = textfile.read()
textfile.close()
print(textcontent)
adjective=input("adjective")
verb=input("verb")
noun=input("noun")
adverb=input("adverb")
textcontent= re.sub(r'ADJECTIVE',adjective,textcontent)
textcontent= re.sub(r'NOUN',noun,textcontent)
textcontent= re.sub(r'ADVERB',adverb,textcontent)
textcontent= re.sub(r'VERB',verb,textcontent)
print(textcontent)
new_fileName = 'new_' + 'source.txt'
new_file = open(new_fileName, 'w')
new_file.write(textcontent)
new_file.close()
print("File is saved as 'new_source.txt'")

答案 2 :(得分:0)

在 Windows10 上使用 python 3.8。用户可以使用评论中提到的代码在那里创建自己的句子。 Python 编程新手。

#python3
#madLibsPrac - to read and change the text files

import os, re

file = input("Create a file name for your work:\n")
madLibsFile = open(file, 'w')
sentence = '''The ADJECTIVE panda walked to the NOUN and then VERB. A nearby NOUN was
unaffected by these events.'''

# user can also add his/her own input using above format, use the line below
# sentence  = input("Enter a string containing these word(ADJECTIVE|VERB|NOUN)\n") 
# and can subsequently make the changes using the same code

madLibsFile.write(sentence)
madLibsFile.close()

def start():

    #Make a file on the current directory.
    fileName = input("Enter a file name:\n")
    existsFile = os.path.abspath(fileName)
    print(existsFile) #Gives the absolute path

    if os.path.exists(existsFile) ==  True:

        textFile = open('madLibs.txt')
        textFileContent = textFile.read()
        textFile.close()

        grammerRegex = re.compile(r"ADJECTIVE|NOUN|VERB|NOUN")
        match = grammerRegex.findall(textFileContent) # Creats a list of all matches


        for i in range(len(match)): # Iterate through the list of matches

            userInput = input("Enter a "+ match[i]+ ":\n")
            textFileContent = textFileContent.replace(match[i], userInput, 1) #updating the textFileContent i.e the string

        print(textFileContent)
        newFileName = "new_" + fileName #Creats a new file 
        newFile = open(newFileName, 'w') # Opens it in write mode
        newFile.write(textFileContent)
        newFile.close()

    else:

        print("The File does not exists.")
        start()

start()