从文件中读取字符串,替换它,并将其存储在新文件中。(Python 3.x版)

2024-10-16 17:17:17 发布

您现在位置:Python中文网/ 问答频道 /正文

创建一个Mad-Libs程序,读入文本文件,让用户在文本文件中出现形容词、名词、副词或动词的任何地方添加自己的文本。例如,文本文件可能如下所示:

The ADJECTIVE panda walked to the NOUN and then VERB. A nearby NOUN was unaffected by these events.

程序将找到这些事件并提示用户替换它们。你知道吗

Enter an adjective:
silly
Enter a noun:
chandelier
Enter a verb:
screamed
Enter a noun:
pickup truck

然后将创建以下文本文件:

The silly panda walked to the chandelier and then screamed. A nearby pickup truck was unaffected by these events.

结果应打印到屏幕上并保存到新的文本文件中。你知道吗

我的代码:

import os

InputFile = open('FileOne.txt','r')
InputContent = InputFile.read()
InputFile.close()

outputFile = open('FileTwo.txt','w')
convert = InputContent
for word in ['NOUN', 'ADJECTIVE', 'VERB']:
    if word in InputContent:
        convert = convert.replace(word, input('Enter %s: ' %word))

outputFile.write(convert)
outputFile.close()

我的文件一的内容是:名词是一个形容词的人。突然名词动词。这个名词现在死了。你知道吗

当我运行代码时:

Enter NOUN: Dave
Enter ADJECTIVE: lovely
Enter VERB: screamed.

它创建输出文本文件FileTwo,但它是空的。你知道吗

输出文件应包含

Dave is a lovely person. Suddenly Dave screamed. Dave is now dead.

我做错什么了?你知道吗

编辑:更改代码。现在可以了。非常感谢你的帮助:D


Tags: 代码程序convertwordadjectivenounenter文本文件
2条回答

在python解释器中尝试代码的简化版本可以非常清楚地显示错误

>>>convert = ''
>>>convert.replace('abc', '123')
''

您将使用空字符串“”并用Dave替换NOUN(不存在),其结果仍然是空字符串。你知道吗

然后将空字符串写入文件2.txt你知道吗

解决方案是对InputContent调用replace()

一个简单的例子是

>>>InputContent = 'Hello NOUN, my name is NOUN'
>>>InputContent.replace('NOUN', 'Dave')
'Hello Dave, my name is Dave'

现在您看到replace()替换搜索词的所有实例(在本例中为名词)

解决这个新问题将留给你做练习

这是因为您试图覆盖的变量convert是一个空字符串。所以当你把输出放在第二个文件里的时候,你实际上什么都没有放进去。你知道吗

如果改为使用convert并将其设置为等于InputContent,则每次替换后都将convert设置为等于convert,则效果很好:

import os

InputFile = open('FileOne.txt','r')
InputContent = InputFile.read()
InputFile.close()

outputFile = open('FileTwo.txt','w')
convert = InputContent
for word in ['NOUN', 'ADJECTIVE', 'VERB']:
    if word in InputContent:
        Convert = convert.replace(word, input('Enter %s: ' %word))
        convert = Convert
outputFile.write(Convert)
outputFile.close()

相关问题 更多 >