我目前正在研究“用python自动化无聊的东西”。我参加了第八章题为“疯狂Libs”的实践项目。任务如下:
Create a Mad Libs program that reads in text fles and lets the user add their own text anywhere the word ADJECTIVE, NOUN, ADVERB, or VERB appears in the text file. For example, a text fle may look like this:
The ADJECTIVE panda walked to the NOUN and then VERB. A nearby NOUN was unaffected by these events.
The program would find these occurrences and prompt the user to replace them.
Enter an adjective: silly
Enter a noun: chandelier
Enter a verb: screamed
Enter a noun: pickup truck
The following text file would then be created:
The silly panda walked to the chandelier and then screamed. A nearby pickup truck was unaffected by these events.
The results should be printed to the screen and saved to a new text file.
我目前的计划如下:
#! python3
# Requests user for an ADJECTIVE, NOUN, ADVERB, and a NOUN
# Replaces the words ADJECTIVE/NOUN/ADVERB/NOUN with the input in a txt file
# Saves the new Mad Lib as a new txt file
import re
reADJECTIVE = re.compile(r'''(ADJECTIVE)''')
reNOUN = re.compile(r'''(NOUN)''')
reVERB = re.compile(r'''(VERB)''')
for i in range(1):
# Gets user input for ADVECTIVE/NOUN/VERB/NOUN
ADJECTIVE = input('Enter an adjective: ')
NOUN = input('Enter a noun: ')
VERB = input('Enter a verb: ')
NOUN2 = input('Enter a noun: ')
madLibFile = open('madlib%s.txt' % (i + 1))
madLibFileContent = madLibFile.read()
madLibFile.close()
madLibFileContent = madLibFileContent.split('. ')
print(madLibFileContent)
newMadLib = re.sub(reADJECTIVE, ADJECTIVE, madLibFileContent[0])
newMadLib = re.sub(reNOUN, NOUN, newMadLib)
newMadLib = re.sub(reVERB, VERB, newMadLib)
newMadLib = newMadLib + '. ' + re.sub(reNOUN, NOUN2, madLibFileContent[1])
print(newMadLib)
对于给定的例子,这个程序可以工作,但是由于我用句号/句点分隔它读入的文件,它只在输入文件的格式为:
ADJECTIVE NOUN ADVERB. NOUN.
并且不适用于任何其他格式,例如:
ADJECTIVE NOUN. ADVERB NOUN.
我最初的想法是使用regex模式:
^{pr2}$如果我们假设任何给定的Mad Lib都遵循相同的形容词-名词-动词-名词的模式,那么这个方法是可行的。在
如果我使用:
re.sub(r'(NOUN)', replacement, someString)
它将用替换替换替换字符串中的NOUN实例。是否可以用不同的内容替换每个捕获组?在
感谢您抽出时间,我希望问题足够清楚:)
诀窍是在
re.sub
中使用一个函数来代替替换字符串。这是一个粗糙的方法。在我没有费心用你的话,只是当时我脑子里出现的任何东西。这是它在使用中的样子。在
^{pr2}$编辑:根据评论添加。
结果:
这是我的代码:
好的,所以上面的行正在打开文件,并且在
^{pr2}$contents
中存储了文件的全部内容。在content
中,单个单词是独立存储的。在regex1负责替换动词、形容词、名词和副词的单个输入。}确保位置和正确的单词被替换。在
content[i]
和{请随意纠正我,或用较短的方法解决这个问题。希望它能解决你的问题。在
相关问题 更多 >
编程相关推荐