Python,如何用文本文件中的不同唯一字符串替换文件中的特定字符串?

时间:2019-11-23 12:14:16

标签: 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
Site 3: x=3,y=0

1 个答案:

答案 0 :(得分: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