简体   繁体   中英

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

So I am looking for easiest way in python to search for a “specific string”(same string, multiple times) and replace each “specific string” with unique value from text file.

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

Here is what I want the result file would look like:

Updatedfile.txt:

Location:
Site 1: x=1,y=0
Site 2: x=2,y=0
Site 3: x=3,y=0

You can create a generator that will yield the replacements, and call next on it each time you make a replacement:

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))

Output:

Site 1: x=1,y=0
Site 2: x=2,y=0
Site 3: x=3,y=0

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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