[英]Automate the boring stuff with python chapter_8 MadLibs
你好,这个练习说:创建一个 Mad Libs 程序,它读入文本文件,并让用户在文本文件中出现单词 ADJECTIVE、NOUN、ADVERB 或 VERB 的任何地方添加他们自己的文本。
textfile = ADJECTIVE panda 走到名词,然后是动词。 附近的 NOUN 没有受到这些事件的影响。
到目前为止我所拥有的是:
import re
#filename = input('Input the Filename: ')
with open('madlibs.txt') as file:
content = file.read()
file.close()
regex = re.compile(r'ADJECTIVE|NOUN|VERB|ADVERB')
#regex = re.compile('[A-Z]{3,}')
matches = regex.findall(content)
#newWord = []
for word in matches:
user_input = input('Enter %s: ' % word)
# newWord.append(user_input)
new_content = content.replace(word,user_input,1)
print(new_content)
我的输入是:
Enter ADJECTIVE: heavy
Enter NOUN: whale
Enter VERB: runs
Enter NOUN: door
我的输出:
The ADJECTIVE panda walked to the door and then VERB. A nearby door was
unnafected by these events.
有人可以向我解释我做错了什么吗? 似乎由于某种原因我无法更改 ADJECTIVE 和 VERB,我还尝试了大写注释的正则表达式,它的作用相同,因此问题出在其他地方。
您需要更改content
,但是由于不是,它会覆盖所做的更改,直到最后一句话:
for word in matches:
user_input = input('Enter %s: ' % word)
content = content.replace(word,user_input) # overwrite content here
print(content)
或者,如果您希望保持content
不变:
new_content = content
for word in matches:
user_input = input('Enter %s: ' % word)
new_content = new_content.replace(word,user_input) # overwrite new_content here
print(new_content)
python中的字符串是不可变的,这意味着它们不会就地更改,而是必须重新分配:
somestring = "this is a string"
for word in ["is", "a"]:
newstring = somestring.replace(word, "aaaa")
print(newstring)
# this is aaaa string
print(somestring)
# this is a string
注意somestring
仍然是原始值。 确实发生了第一次replace
,只是当重新分配somestring.replace("a", "aaaa")
的结果时,它才被覆盖。
分为步骤:
somestring = "this is a string"
newstring = somestring.replace("is", "aaaa")
# this aaaa a string
newstring = somestring.replace("a", "aaaa")
# this is aaaa string
#! /usr/bin/python3
# mad_libs.py - Playing mad libs game
# Usage: python3 mad_libs.py save - Save a mad lib phrase from clip board
# python3 mad_libs.py - Play the mad libs game.
# Caution: Must save at least one phrase before playing.
import shelve, pyclip, random, sys, re
import pyinputplus as pyi
# Open shelve file
shelfFile = shelve.open('mad_libs')
# Add phrase to the database by pasting from clipboard
if len(sys.argv) == 2 and sys.argv[1] == 'save':
shelfFile[str(len(shelfFile))] = pyclip.paste().decode()
print("Phrase saved.")
sys.exit()
# Get a random phrase from database and display
phrase = shelfFile[str(random.randrange(len(shelfFile)))]
# Regex for finding match
matLibsRegex = re.compile(r'(ADJECTIVE)|(NOUN)|(VERB)|(ADVERB)')
print(phrase)
while True:
# Find all the matches and replace with user's input
match = matLibsRegex.search(phrase)
if match == None: # Return None if there is no match
break
prompt = f"Enter an {match.group().lower()}: " if match.group(
)[0] in 'Aa' else f"Enter a {match.group().lower()}: "
substitute = pyi.inputStr(prompt)
phrase = phrase.replace(match.group(), substitute, 1) # Replace the fill-in space with user's input
# Print the final phrase and save it to file
print(phrase)
result = open('mad_libs_result.txt', 'a')
result.write(phrase + '\n')
result.close()
shelfFile.close()
由于这篇文章是关于 mad libs 的,我想在这里为即将到来的学习者放下我的解决方案。 我结合了 Mad Libs 练习和 Extend Multi-Clipbaord 练习的功能。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.