Python3:文本的副本,有一些变化

2024-04-26 07:52:36 发布

您现在位置:Python中文网/ 问答频道 /正文

我得到了这个原始的源文本文件:

Hello {Jane Peter},
I send a email to your address {Jane@a.com Peter@a.com}.

我需要为每个人创建两个文件副本: (items具有相同的索引-第一个{}中的Jane是forJane@a.com 在第二个{})

Hello Jane,
I send a email to your address Jane@a.com.

第二个是:

Hello Peter,
I send a email to your address Peter@a.com

因此,关键是从{}中选择项,并使用select和create命令将整个{}子化,以创建正确数量的源文本副本


Tags: 文件tocomsendhelloyouraddressemail
3条回答

您可以使用Formatter.parse从占位符获取姓名/电子邮件:

from string import Formatter

s = """Hello {Jane Peter},
I send a email to your address {Jane@a.com Peter@a.com}."""

names, emails = (p for _, p, _, s in Formatter().parse(s) if p)
s = s.replace(names,"").replace(emails,"")

for name, email in zip(names.split(), emails.split()):
    print(s.format(name, email))

输出:

Hello Jane,
I send a email to your address Jane@a.com.
Hello Peter,
I send a email to your address Peter@a.com.

使用这个正则表达式匹配括号,然后遍历列表并生成所需的字符串

import re
matches = re.findall(r'\{([^}]+)\}', s)
# you should verify that matches indeed contains two elements
names = matches[0].split()
mails = matches[1].split()

您可以使用以下代码:

import re

s = '''Hello {Jane Peter},
I send a email to your address {Jane@a.com Peter@a.com}.'''

count = re.search('{(.*?)}', s).group(1).count(' ')
for i in range(count + 1):
    print(re.sub('{(.*?)}', lambda x: x.group(1).split()[i], s))

输出:

Hello Jane,
I send a email to your address Jane@a.com.
Hello Peter,
I send a email to your address Peter@a.com.

它将首先使用^{}找到要替换的第一个组,然后计算匹配中的空格数,以确定需要创建多少个副本。当然,这仅在模板中使用的字符串不包含任何空格时有效。如果您已经知道需要多少副本,则可以跳过此操作

下一段代码将使用^{}在循环中生成副本{(.*?)}将匹配所有需要替换的标记,并捕获括号中的文本。然后它将分割捕获的文本并使用当前正在处理的索引中的项

虽然该示例在这种特定场景中有效,但我建议检查此类任务的真实模板库^{}是一种流行的选择

相关问题 更多 >