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

Python 获取从一个文本到另一个文本文件的值,python,python-3.x,Python,Python 3.x,如何将一个文本中的值附加到特定位置的另一个文本文件中 1.txt date : 26/04 test_name : Cs link1 : xyz link2 : abc second.txt Pending of taking test {test_name} was due on {date}. Follow the below link X_link : {link1} --> replace with xyz from

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

1.txt

date : 26/04
test_name : Cs
link1 : xyz
link2 : abc
second.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
使用正则表达式:

Ex:

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
输出:

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

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

def parse(text):
    lines = text.split("\n")
    data = {}
    for line in lines:
        key, value = line.split(":")
        data[key] = value
    return data
(我假设读取文件不是问题)
如果使用,则替换文件内容会更简单。 然后你可以做如下事情:

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

您的第二个文件已经准备好了
格式
支持的占位符。因此,配方如下:

  • 将第一个文件解析到替换字典中
  • 逐行读取第二个文件
  • 对于每一行,根据指令替换内容
  • 打印格式化行:
replacements={}
打开('one.txt')作为文件1:
对于文件1中的行:
名称,值=行。拆分(“:”)
替换[name.strip()]=value.strip()
打开('secon.txt')作为文件2:
对于文件2中的行:
打印(行格式(**替换),结束=“”)

我得到的地点日期只有“26”而不是“26/04”@RakeshUse
(\w+)\s*:\s*([\w\/]+)
嗨,如果我给计算机科学,它只给计算机输出。我试图给出
/s
,但其他值受到干扰@Rakesh
(\w+\s*:\s*([\w\/\s]+)
需要打印输出,无需保存在特定文件中。谢谢@TomerikooOh这个问题不清楚。我以为你想替换这个文件。这使它变得更简单。请参阅编辑
ValueError:太多值无法解包(预期为2)
如果我在第一个文件中给定了任何URL,并且我希望将内容保存在变量中并重新使用我们正在打印的内容,则会出现错误@请用a编辑问题,以便我可以测试@manojkumar@manojkumar因为那条线在一个循环中。您将只获得最后一次迭代的值。尝试在循环外部初始化空字符串
cont='
,然后在循环内部执行
cont+=line…