gpt4 book ai didi

python - 当我尝试在 linux 中使用 f.open python 更改它们时,内容会重复

转载 作者:塔克拉玛干 更新时间:2023-11-02 23:54:41 25 4
gpt4 key购买 nike

我的代码是这种格式

#!/usr/bin/python

fout = open("names2", "w")
fin = open("names", "r")

for line in fin:
fout.write(line.replace('Smith','Mr.Smith'))
fout.write(line.replace('Walker','Mr.Walker'))

fout.close()

我的示例文件是

Smith           Anderson        Clark           Wright          Mitchell
Johnson Thomas Rodriguez Lopez Perez
Williams Jackson Lewis Hill Roberts
Jones White Lee Scott Turner
Brown Harris Walker Green Phillips
Davis Martin Hall Adams Campbell
Miller Thompson Allen Baker Parker
Wilson Garcia Young Gonzalez Evans
Moore Martinez Hernandez Nelson Edwards
Taylor Robinson King Carter Collins

不是让 Smith 由​​ Mr.Walker 改为 Mr.Smith 和 Walker,而是我得到

Mr.Smith                Anderson        Clark           Wright          Mitchell
Smith Anderson Clark Wright Mitchell
Johnson Thomas Rodriguez Lopez Perez
Johnson Thomas Rodriguez Lopez Perez
Williams Jackson Lewis Hill Roberts
Williams Jackson Lewis Hill Roberts
Jones White Lee Scott Turner
Jones White Lee Scott Turner
Brown Harris Walker Green Phillips
Brown Harris Mr.Walker Green Phillips
Davis Martin Hall Adams Campbell
Davis Martin Hall Adams Campbell
Miller Thompson Allen Baker Parker
Miller Thompson Allen Baker Parker
Wilson Garcia Young Gonzalez Evans
Wilson Garcia Young Gonzalez Evans
Moore Martinez Hernandez Nelson Edwards
Moore Martinez Hernandez Nelson Edwards
Taylor Robinson King Carter Collins
Taylor Robinson King Carter Collins

这意味着对于每个 for,文件都会创建一个额外的实例并且行会重复,这是我不希望发生的。我有解决办法吗?我有 Python 2.4.3。谢谢!

最佳答案

那是因为你把这行写了两次。

将循环更改为:

for line in fin:
line = line.replace('Smith','Mr.Smith')
line = line.replace('Walker','Mr.Walker')
fout.write(line)

关于python - 当我尝试在 linux 中使用 f.open python 更改它们时,内容会重复,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22049340/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com