如何在字符串模板中替换NAME之类的子字符串?

Mar*_*ura 2 python replace substring template-strings

我有一个包含我想要替换的子串的字符串,例如

text = "Dear NAME, it was nice to meet you on DATE. Hope to talk with you and SPOUSE again soon!"
Run Code Online (Sandbox Code Playgroud)

我有一个格式的csv(第一行是标题)

NAME, DATE, SPOUSE
John, October 1, Jane
Jane, September 30, John
...
Run Code Online (Sandbox Code Playgroud)

我正在尝试循环遍历csv文件中的每一行,text使用与原始子字符串匹配的标题行的列中的csv元素替换子字符串.我有一个名单matchedfields,其中包含在csv标题行中找到的所有字段text(如果csv 中有一些列我不需要使用).我的下一步是遍历每个csv行并将匹配的字段替换为该csv列中的元素.要做到这一点,我正在使用

with open('recipients.csv') as csvfile:
 reader = csv.DictReader(csvfile)
 for row in reader:
     for match in matchedfields:
        print inputtext.replace(match, row[match])
Run Code Online (Sandbox Code Playgroud)

我的问题是,它只用textcsv中的相应元素替换第一个匹配的子字符串.有没有办法同时进行多次替换,所以我最终得到了

"Dear John, it was nice to meet you on October 1. Hope to talk with you and Jane again soon!"

"Dear Jane, it was nice to meet you on September 30. Hope to talk with you and John again soon!"
Run Code Online (Sandbox Code Playgroud)

dan*_*gom 6

我认为真正的方法是使用字符串模板.让您的生活轻松.

这是一个在Python2和3下工作的通用解决方案:

import string

template_text = string.Template(("Dear ${NAME}, "
                                 "it was nice to meet you on ${DATE}. "
                                 "Hope to talk with you and ${SPOUSE} again soon!"))
Run Code Online (Sandbox Code Playgroud)

然后

import csv

with open('recipients.csv') as csvfile:
    reader = csv.DictReader(csvfile)
    for row in reader:
        print(template_text.safe_substitute(row))
Run Code Online (Sandbox Code Playgroud)

现在,我注意到你的csv有点空白,所以你必须先处理它(或调整csv阅读器或模板的调用).