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

2024-10-01 04:45:26 发布

您现在位置:Python中文网/ 问答频道 /正文

所以我正在寻找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

Tags: 文件方法字符串txtsitelocation文本文件样子
1条回答
网友
1楼 · 发布于 2024-10-01 04:45:26

您可以创建生成替换的生成器,并在每次进行替换时对其调用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

相关问题 更多 >