【发布时间】:2017-03-09 09:17:52
【问题描述】:
我有一个包含要替换的子字符串的字符串,例如
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])
我的问题是这只会用 csv 中的适当元素替换 text 中的第一个匹配子字符串。有没有办法同时进行多个替换,所以我最终得到了
"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!"
【问题讨论】:
标签: python replace substring template-strings