python - 使用 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 中但是我不明白该怎么做
解决方案
您可以按如下方式简化代码。
代码
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'
推荐阅读
- python - 带有返回值的类的 Python 多线程
- c++ - MSVC 可变参数模板处理错误?
- javascript - Javascript将数组值从布尔值切换为字符串
- c++ - 为什么在 `std::add_pointer_t` 中需要 SFINAE?
- elasticsearch - 如何提高弹性搜索查询结果(异常值)中最受欢迎的(前四分之一)
- typescript - 如何将类型定义为定义为 [key: string] 键/值结构的对象键列表 - TypeScript
- java - 如何在 Gradle 中使用 Quarkus gRPC 扩展?
- image - ffmpeg:将多个图像叠加到视频中
- c - 如何从c中的函数返回字符串
- javascript - 根据在第二个数组中具有匹配记录的列名更改 javascript 中对象数组中的键名