2

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

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])

我的问题是,这只会用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!"
4

3 回答 3

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!"))

接着

import csv

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

现在,我注意到你的 csv 有点搞砸了空格,所以你必须先处理好这个问题(或者调整对 csv 阅读器或模板的调用)。

于 2016-10-26T21:10:03.990 回答
3

问题是它inputtext.replace(match, row[match])不会更改inputtext变量,它只会创建一个您不存储的新字符串。尝试这个:

import copy 

with open('recipients.csv') as csvfile:
    reader = csv.DictReader(csvfile)
    for row in reader:
        inputtext_copy = copy.copy(inputtext) ## make a new copy of the input_text to be changed.
        for match in matchedfields:
            inputtext_copy = inputtext_copy.replace(match, row[match]) ## this saves the text with the right 
        print inputtext ## should be the original w/ generic field names 
        print inputtext_copy ## should be the new version with all fields changed to specific instantiations
于 2016-10-26T21:01:57.667 回答
2

You should reassign the replaced string to the original name so the previous replacements are not thrown away:

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

On another note, you could update the original string using string formatting with a little modification to the string like so:

text = "Dear {0[NAME]}, it was nice to meet you on {0[DATE]}. Hope to talk with you and {0[SPOUSE]} again soon!"

with open('recipients.csv') as csvfile:
    reader = csv.DictReader(csvfile)
    for row in reader:
        inputtext = text.format(row)
        print inputtext

That formats the string with the dictionary in one step, without having to make replacements iteratively.

于 2016-10-26T20:56:47.080 回答