替换文件中的文本就是创建复制行



我正在学习Python。

我已经知道R了,但我承认我在努力学习Python。

我正在使用这里找到的代码

这是代码:

checkWords = ("old_text1","old_text2","old_text3","old_text4")
repWords = ("new_text1","new_text2","new_text3","new_text4")
for line in f1:
for check, rep in zip(checkWords, repWords):
line = line.replace(check, rep)
f2.write(line)
f1.close()
f2.close()

输入如下所示:

This is old_text1.
This is old_text2.
This is old_text3.
This is old_text4.

上面的代码运行良好,我得到了预期的输出。

然而,如果我试图将以上内容放入函数中,比如。。。

def test(f1, f2):
checkWords = ("old_text1","old_text2","old_text3","old_text4")
repWords = ("new_text1","new_text2","new_text3","new_text4")

for line in f1:
for check, rep in zip(checkWords, repWords):
line = line.replace(check, rep)
f2.write(line)
f1.close()
f2.close()

file1 = open('test_file1.txt', 'r')
file2 = open('test_file2.txt', 'w')
test(file1, file2)

输出如下所示:

This is new_text1.
This is new_text1.
This is new_text1.
This is new_text1.


This is old_text2.
This is new_text2.
This is new_text2.
This is new_text2.


This is old_text3.
This is old_text3.
This is new_text3.
This is new_text3.


This is old_text4.
This is old_text4.
This is old_text4.
This is new_text4.

在某个地方,它看起来像是在循环通过函数,但我不知道是怎么回事。此外,当它在第2-4次循环时,看起来输出不正确。

我试着在函数之外使用checkWords和repWords,但无济于事。

有人能向我解释为什么会发生这种情况,以及如何解决吗?

提前谢谢。

Dan

您的函数会更改print的频率。您的代码打印";新的";行,无论您是否进行了替换。最简单的更改是通过一个简单的检查来更改代码:

for line in f1:
for check, rep in zip(checkWords, repWords):
if check in line:
line = line.replace(check, rep)
f2.write(line)
break  # This saves superfluous checks

最新更新