获取从一个文本到另一个文本文件的值

q3aa0525  于 2021-07-13  发布在  Java
关注(0)|答案(3)|浏览(320)

如何将一个文本中的值附加到特定位置的另一个文本文件中?
一个.txt

date : 26/04
test_name : Cs
link1 : xyz
link2 : abc

秒.txt

Pending of taking test {test_name} was due on {date}. Follow the below link

X_link : {link1} --> replace with xyz from one.txt

y_link : {link2} --> replace with abc from one.txt

需要将second.txt中的one.txt值放在{}中提到的名称所在的位置。
输出:

Pending of taking test Cs was due on 26/04. Follow the below link

X_link : xyz

y_link : abc
oxf4rvwz

oxf4rvwz1#

使用正则表达式:
前任:

import re

# file_one.read()

one = """date : 26/04
test_name : Cs
link1 : xyz
link2 : abc"""

# file_second.read()

second = """Pending of taking test {test_name} was due on {date}. Follow the below link
X_link : {link1} --> replace with xyz from one.txt
y_link : {link2} --> replace with abc from one.txt"""

for k, v in re.findall(r"(\w+)\s*:\s*(\w+)", one):
    second = re.sub(f"{{{k}}}", v, second)    # substitute value
print(second)

输出:

Pending of taking test Cs was due on 26. Follow the below link
X_link : xyz --> replace with xyz from one.txt
y_link : abc --> replace with abc from one.txt
ctehm74n

ctehm74n2#

你的第二份文件已经准备好了 format 支持的占位符。所以配方如下:
将第一个文件解析为替换字典。
逐行读取第二个文件。
对于每一行,根据dict替换内容。
打印格式化行:

replacements = {}

with open('one.txt') as file1:
    for line in file1:
        name, value = line.split(':')
        replacements[name.strip()] = value.strip()

with open('secon.txt') as file2:
    for line in file2:
        print(line.format(**replacements), end='')
e7arh2l6

e7arh2l63#

这样就可以解析文件。相对简单

def parse(text):
    lines = text.split("\n")
    data = {}
    for line in lines:
        key, value = line.split(":")
        data[key] = value
    return data

(我假设读取文件不是问题)
如果使用jinja,替换文件内容会更简单。然后你可以这样做:

template.render(test_name=data["test_name"])

相关问题