1

你好,这个练习说:创建一个 Mad Libs 程序,它读取文本文件并允许用户在文本文件中出现单词 ADJECTIVE、NOUN、ADVERB 或 VERB 的任何位置添加自己的文本。

textfile = 形容词 panda 走到名词和动词。附近的一个名词没有受到这些事件的影响。

到目前为止我所拥有的是:

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,我还尝试了大写的注释正则表达式,它也是如此,所以问题出在其他地方。

4

2 回答 2

2

你需要改变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
于 2019-05-22T20:53:10.767 回答
0
#! /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 练习的功能。

于 2021-10-16T07:38:30.507 回答