Python,如何用文本文件中不同的唯一字符串替换文件中的特定字符串?
所以我正在寻找python中搜索“特定字符串”(相同字符串,多次)并用文本文件中的唯一值替换每个“特定字符串”的最简单方法 OriginalFile.txt:Python,如何用文本文件中不同的唯一字符串替换文件中的特定字符串?,python,search,replace,Python,Search,Replace,所以我正在寻找python中搜索“特定字符串”(相同字符串,多次)并用文本文件中的唯一值替换每个“特定字符串”的最简单方法 OriginalFile.txt: Location: Site 1: x=0,y=0 Site 2: x=0,y=0 Site 3: x=0,y=0 Filewithvalues.txt: x=1 x=2 x=3 下面是我想要的结果文件的样子: Updatedfile.txt: Location: Site 1: x=1,y=0 Site 2: x=2,y=0 Sit
Location:
Site 1: x=0,y=0
Site 2: x=0,y=0
Site 3: x=0,y=0
Filewithvalues.txt:
x=1
x=2
x=3
下面是我想要的结果文件的样子:
Updatedfile.txt:
Location:
Site 1: x=1,y=0
Site 2: x=2,y=0
Site 3: x=3,y=0
您可以创建生成替换的生成器,并在每次进行替换时对其调用
next
:
import re
original_file = """Site 1: x=0,y=0
Site 2: x=0,y=0
Site 3: x=0,y=0
""".splitlines()
replacements_file = """x=1
x=2
x=3
""".splitlines()
# This generator expression will iterate on the lines of replacements_file
# and yield the next replacement on each call to next(replacements)
replacements = (line.strip() for line in replacements_file)
out = []
for line in original_file:
out.append(re.sub(r'x=0', next(replacements), line))
print('\n'.join(out))
输出:
Site 1: x=1,y=0
Site 2: x=2,y=0
Site 3: x=3,y=0
您好,您在示例中寻找的“特定字符串”是什么?我假设它是“x=0”
?另外,请展示一些您尝试过的代码,因为在帮助您之前,您已经尝试过一些东西,这感觉很好。