【问题标题】:Python, How to replace a specific string from file with different unique strings from a text file?Python,如何用文本文件中的不同唯一字符串替换文件中的特定字符串?
【发布时间】:2020-03-19 07:23:37
【问题描述】:

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

【问题讨论】:

  • 您好,您在示例中要查找的“特定字符串”是什么?我想它会是"x=0"?另外,请展示一些您尝试过的代码,因为在帮助您之前感觉您已经尝试过一些东西是很好的。

标签: python search replace


【解决方案1】:

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

【讨论】:

    猜你喜欢
    • 2015-07-31
    • 1970-01-01
    • 2014-06-21
    • 2021-02-14
    • 1970-01-01
    • 2021-11-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多