首页 > 解决方案 > 使用 python madlibs 程序自动化无聊的东西

问题描述

我是一名初学者程序员,所以请放心,我正在做这本书并坚持练习 方向如下 Mad Libs 创建一个 Mad Libs 程序,它读取文本文件并让用户在任何位置添加自己的文本 ADJECTIVE 、名词、副词或动词出现在文本文件中。例如,一个文本文件可能如下所示: ADJECTIVE panda 走到名词,然后是动词。附近的一个名词不受这些事件的影响。程序会发现这些事件并提示用户替换它们。输入形容词:silly 输入名词:chandelier 输入动词:screaled 输入名词:pick truck 随后将创建以下文本文件: 傻熊猫走到枝形吊灯前,然后尖叫。附近的一辆皮卡车没有受到这些事件的影响。结果应打印到屏幕上并保存到新的文本文件中。

import pyperclip

def ML(file):
Ofile=open(file)
x=Ofile.read()
y=x.split()
for i in range(len(y)):
    if y[i]=='ADJECTIVE':
        print('what is your adjective?')
        replacment=input()
        y[i]=replacment
        for i in range(len(y)):
            if y[i]=='NOUN':
                print('what is your noun?')
                replacment=input()
                y[i]=replacment
                for i in range(len(y)):
                    if y[i]=='VERB':
                        print('what is your verb?')
                        replacment=input()
                        y[i]=replacment
for i in range(len(y)):
    print(y[i],end=' ')
Nfile=open('madlibs3.txt.txt','w')
Nfile.write(x)
Nfile.close()
Ofile.close()
print('write your file path.')
Afile = input()
ML(Afile)

我的问题是我的代码不起作用

我很确定主要问题是新字符串没有保存在变量 x 中但是我不明白该怎么做

标签: python

解决方案


您可以按如下方式简化代码。

代码

def ML(input_file, output_file):
  # Use with since it automatrically closes files
  with open(input_file, 'r') as ifile, open(output_file, 'w') as ofile:
    result = []
    for line in ifile:  # looping through lines in file
      new_line = []
      for word in line.rstrip().split():  # looping through words in a line
        if word in ('NOUN', 'ADJECTIVE', 'VERB'):  # word is one of the ones we're checing for
          replace_word = input(f'What is your {word.lower()}?')
          new_line.append(replace_word)  # use replacement word
        else:
          new_line.append(word)          # use original word
      result.append(' '.join(new_line))  # form new space separated line

    # Write result
    ofile.write('\n'.join(result))       # join all lines together with carriage returns
                                         # and write to file

    return result                        # Return result to caller

用法

print(ML('input.txt', 'output.txt'))     # print results to screen and
                                         # writes to 'output.txt'

推荐阅读