繁体   English   中英

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

[英]Python, How to replace a specific string from file with different unique strings from a text file?

所以我在 python 中寻找最简单的方法来搜索“特定字符串”(相​​同的字符串,多次)并用文本文件中的唯一值替换每个“特定字符串”。

原始文件.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

这是我希望结果文件的样子:

更新文件.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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM