[英]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)
也許您可以嘗試在將文件與正則表達式匹配並修改它之前讀出文件的內容,在以下步驟中。
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
def get_file_data(file):
return [line.strip() for line in open(file)]
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
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.