簡體   English   中英

將一個文本文件中的值替換為另一個

[英]Replace value from one text file into another

用另一個文件中的另一行文本替換一行文本。 給定一個文本文件(file.txt):

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

宏 (macro.txt) 的相關替代品:

macro:jason
gas:super

制作:

cat jason is cool
dog super is cool

我一直在考慮查找和替換,但是,我的案例需要列表中的許多宏替換。 一切都在一個文本文件中。

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)
    

也許您可以嘗試在將文件與正則表達式匹配並修改它之前讀出文件的內容,在以下步驟中。

  1. 讀取文件內容:macro.txt 並制作映射字典
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. 從文件中獲取原始數據:file.txt
def get_file_data(file):
    return [line.strip() for line in open(file)]
  1. 用正則表達式匹配文件,如果有任何需要替換的地方就替換它
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. 將最終數據寫入文件
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))

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM