我有一个包含要替换的子字符串的字符串,例如
text = "Dear NAME, it was nice to meet you on DATE. Hope to talk with you and SPOUSE again soon!"
我有一个格式的 csv(第一行是标题)
NAME, DATE, SPOUSE
John, October 1, Jane
Jane, September 30, John
...
我正在尝试遍历 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])
我的问题是,这只会用text
csv 中的适当元素替换第一个匹配的子字符串。有没有办法同时进行多个替换所以我最终得到
"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!"