0

所以我一直在用“用 Python 自动化无聊的东西”来学习 Python,我在第 8 章-MadLibs 项目中偶然发现了一个问题。我知道我的代码无法像所需的问题那样从文件中读取,因为我想首先确保核心部分正常工作。我创建的代码可以检测输入文本是否有任何“形容词”、“动词”、“副词”和“名词”,并将它们替换为用户输入的单词,最后创建一个包含这些更改的文本文件。该代码具有用于检测名词、动词、副词和形容词的相同代码行。

import os
def MadLibs(what):
input_text=str(what)
text=input_text.split()
j=0
for j in range(len(text)-1):
    if text[j].lower()=='adjective':
        adj=input('Enter an adjective:\n')
        text[j]=adj
    elif text[j].lower()=='verb':
        vrb=input('Enter a verb:\n')
        text[j]=vrb

    elif text[j].lower()=='adverb':
        adv=input('Enter an adverb:\n')
        text[j]=adv

    elif text[j].lower()=='noun':
        noun=input('Enter a noun:\n')
        text[j]=noun
    
    
output = ' '.join(text)
textFile=open('D:\\Python\\Automate stuffs with Python\\ch.8 project2 results.txt','w')
textFile.write(output)
textFile.close()

但是,当我运行代码时,它找不到“动词”,因为代码没有要求“动词”的替换词。谁能解释为什么?这是结果。

>>> MadLibs('The ADJECTIVE panda walked ADVERB to the NOUN and then VERB. A nearby NOUN was unaffected by these events.')
   Enter an adjective:
   s
   Enter an adverb:
   f
   Enter a noun:
   g
   Enter a noun:
   t
4

1 回答 1

0

尝试如下更改 for 循环。

for i,j in enumerate( text ):
    if j == 'e':
        text[i] = input('')

于 2021-06-23T14:03:04.630 回答