如何使用循环计数器替换文件中的字符串
how to replace strings in a file using a loop counter
我有一个文件名为:my_file.txt
在这个 my_file.txt
中,我有一些字符串,例如:
name1 name1 name1 name1 name1 name1 name1 name1 name1 name1
我需要在 1 到 10 上做一个批量循环计数器,看起来像:
name1 name2 name3 name4 name5 name6 name7 name8 name9 name10
到目前为止我只有这个,我在这里找到的:
https://www.geeksforgeeks.org/how-to-search-and-replace-text-in-a-file-in-python
但这只是将一个字符串换成另一个字符串。我需要使用计数器。
search_text = "dummy"
replace_text = "replaced"
with open(r'my_file.txt', 'r') as file:
data = file.read()
data = data.replace(search_text, replace_text)
with open(r'my_file.txt', 'w') as file:
file.write(data)
print("Text replaced")
您可以简单地进行迭代替换,每次替换一次。
在字符串非常大的情况下使用块来提高性能
with open(r'my_file.txt', 'r') as file:
data = file.read()
search_text = "dummy"
replace_text = "replaced"
n_replaced = 0
index = 0
chunks = []
while True:
index = data.find(search_text)
if index == -1:
break
replace_text_counter = f"{replace_text}{n_replaced}"
chunks.append(data[:index])
data = data[index:].replace(search_text, replace_text_counter, 1)
n_replaced += 1
chunks.append(data)
with open(r'my_file.txt', 'w') as file:
file.write("".join(chunks))
print("Text replaced")
忽略你的情况下的读写文件和行。我给出的代码只是处理你给的字符串行 name1 name1 name1 name1 name1 name1 name1 name1 name1 name1
:
string = "name1 name1 name1 name1 name1 name1 name1 name1 name1 name1"
li = string.split()
i=0
for i<len(li):
li[i]=li[i].replace("1",i+1)
return ' '.join(li)
我有一个文件名为:my_file.txt
在这个 my_file.txt
中,我有一些字符串,例如:
name1 name1 name1 name1 name1 name1 name1 name1 name1 name1
我需要在 1 到 10 上做一个批量循环计数器,看起来像:
name1 name2 name3 name4 name5 name6 name7 name8 name9 name10
到目前为止我只有这个,我在这里找到的:
https://www.geeksforgeeks.org/how-to-search-and-replace-text-in-a-file-in-python
但这只是将一个字符串换成另一个字符串。我需要使用计数器。
search_text = "dummy"
replace_text = "replaced"
with open(r'my_file.txt', 'r') as file:
data = file.read()
data = data.replace(search_text, replace_text)
with open(r'my_file.txt', 'w') as file:
file.write(data)
print("Text replaced")
您可以简单地进行迭代替换,每次替换一次。
在字符串非常大的情况下使用块来提高性能
with open(r'my_file.txt', 'r') as file:
data = file.read()
search_text = "dummy"
replace_text = "replaced"
n_replaced = 0
index = 0
chunks = []
while True:
index = data.find(search_text)
if index == -1:
break
replace_text_counter = f"{replace_text}{n_replaced}"
chunks.append(data[:index])
data = data[index:].replace(search_text, replace_text_counter, 1)
n_replaced += 1
chunks.append(data)
with open(r'my_file.txt', 'w') as file:
file.write("".join(chunks))
print("Text replaced")
忽略你的情况下的读写文件和行。我给出的代码只是处理你给的字符串行 name1 name1 name1 name1 name1 name1 name1 name1 name1 name1
:
string = "name1 name1 name1 name1 name1 name1 name1 name1 name1 name1"
li = string.split()
i=0
for i<len(li):
li[i]=li[i].replace("1",i+1)
return ' '.join(li)