0

在使用 Python 自动化无聊的东西中做一个练习,这是一个简单的 MadLibs 程序。

需要从文件中读取字符串,将其转换为列表,用用户输入替换某些单词(名词、动词等),然后加入该列表并将新列表写入文件。

我的程序读取、收集用户输入并识别单词,但无法将输入交换为现有单词......尝试了 List Comprehension、枚举和简单地设置 word == 响应。TIA

path = ('/Users/XXXXX/Desktop/MadLibs/ML1.txt')

MadLib = open(path)

content = MadLib.read()
content = 'The ADJECTIVE panda walked to the NOUN and then VERB.'
content = content.split()
MadLib.close()



for word in content:
    if word == word.upper() and len(word) > 1:
        word = word.replace('.','')
        response = input(f"Enter a {word} \n")
        [response for word in content if response]

content = ' '.join(content)

ML1 = open('ML1.txt', 'w')
ML1.write(content)
ML1.close()

MadLib = open(path)
output = MadLib.read()
MadLib.close()

print(output)
4

2 回答 2

1

我和 Ahndwoo 有类似的言论。但我不建议使用content.replace,因为替换会干扰搜索。下面是另一个版本,为了安全起见,还有第二个列表。

content = 'The ADJECTIVE panda walked to the NOUN and then VERB.'
content = content.split()

new_content = []

for word in content:
    if word == word.upper() and len(word) > 1:
        word = word.replace('.', '')
        response = input("Enter a replacement for {}: ".format(word))
        new_content.append(response)
    else:
        new_content.append(word)

new_content = " ".join(new_content)
于 2019-10-11T19:24:36.630 回答
0

您已经在代码中使用了所需的功能:replace()再次使用!

content = 'The ADJECTIVE panda walked to the NOUN and then VERB.'.split()

for word in content:
    if word == word.upper() and len(word) > 1:
        word = word.replace('.','')
        response = input(f"Enter a {word} \n")
        content = content.replace(word, response, 1)

添加1作为的第三个参数replace意味着它只会替换它找到的那个单词的第一个实例。因此,如果您有多个名词或形容词,它只会替换其中一个,而不是全部。

当然,如果打算用相同的响应替换所有单词,这将不起作用。如果那是您打算做的,那么您实际上需要重新制作您的列表:

content = 'The ADJECTIVE panda walked to the NOUN and then VERB.'.split()

for word in content:
    if word == word.upper() and len(word) > 1:
        word = word.replace('.','')
        response = input(f"Enter a {word} \n")
        content = [response if w.replace('.', '') == word else w for w in content]

content = ' '.join(content)

在这种情况下,这将起作用,但它仍会提示您输入每种单词的第二个、第三个实例,即使它们不会被使用。您可以创建一个集合,在其中添加已替换的单词,并对照它检查当前单词,以免提示用户输入它们。

于 2019-10-11T19:16:04.343 回答