简体   繁体   中英

Replace value from one text file into another

Replace line of text with another line of text from another file. Given a text file (file.txt):

cat `macro` is cool
dog `gas` is cool

Associated substitute for macro (macro.txt):

macro:jason
gas:super

to make:

cat jason is cool
dog super is cool

I was thinking along the lines of find and replace, however, my case requires many macro substitutes from the list. Everything is in a text file.

with open('file.txt',r) as A:
with open('macro.txt',r) as B:
macro=A.read()
text=B.read()
for l in text:
  for i in macro:
    if i=l:
      A=A.replace(i,l)
    

Perhaps you could try reading out the contents of the file before matching it with a regular expression and modifying it, in the following steps.

  1. read the contents of the file:macro.txt and make a mapping dictionarY
def get_macro(file):
    res = {}
    with open(file) as f:
        for line in f:
            k, v = line.strip().split(":")
            res[f'`{k.strip()}`'] = v.strip()
    # {"`macro`": "jason", ......}
    return res 
  1. get the original data from the file: file.txt
def get_file_data(file):
    return [line.strip() for line in open(file)]
  1. match the file with a regular expression and replace it if there is anything that needs to be replaced
def update_data(to_be_replace, mapping):
    for line_index, line_data in enumerate(to_be_replace):
        block = re.findall("`.*`", line_data)
        for item in block:
            line_data = line_data.replace(item, mapping[item])
        file_data[line_index] = line_data
  1. write the final data to the file
macro = get_macro("macro.txt")
file_data = get_file_data("file.txt")
update_data(file_data, macro)

with open("file.txt", "w", encoding="utf-8") as f:
    f.write("\n".join(file_data))

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