替换文本模板中的变量

时间:2018-10-25 09:37:21

标签: python string templates

所以我的文本文件中显示了这样的内容:

Dear $name,
\n\n
Thank you for participating in our study on working memory and musical training!
\n\n
You are receiving this email because you said that you were interested in receiving your results of the tests that you took on your musical and non-musical abilities.
\n\n
Your results are below:
\n\n
Test 1: $score1
\n
Test 2: $score2
\n
Test 3: $score3
\n
Test 4: $score4
\n
Test 5: $score5
\n
Test 6: $score6
\n
\n
Thanks again from all of our research team.

\n\n
Seb

我想做的就是用适合每个人的数据替换此文件中的变量($name$score1$score2等。)

我可以这样做吗?将变量存储在文本文件中并访问它们?还是有更好的方法呢?

编辑:

尝试使用@Guilio的示例。

我收到以下错误:AttributeError:'list'对象没有属性'split'

import csv
with open('email.csv', newline='') as csvfile:
    scores = csv.reader(csvfile)
    for row in scores:
        name,score1,score2,score3,score4,score5,score6=[col for col in row.split(';') if col!='']
        text="""Dear {name},

        Thank you for participating in our study on working memory and musical training!

        You are receiving this email because you said that you were interested in receiving your results of the tests that you took on your musical and non-musical abilities.

        Your results are below:


        Test 1: {score1}

        Test 2: {score2}

        Test 3: {score3}

        Test 4: {score4}

        Test 5: {score5}

        Test 6: {score6}

        Thanks again from all of our research team.


        Seb""".format(**score_dict)
        print(text)

1 个答案:

答案 0 :(得分:0)

创建一个“模板”,然后使用存储在字典中的值填写占位符{name}

text="""Dear {name},

Thank you for participating in our study on working memory and musical training!

You are receiving this email because you said that you were interested in receiving your results of the tests that you took on your musical and non-musical abilities.

Your results are below:


Test 1: {score1}

Test 2: {score2}

Test 3: {score3}

Test 4: {score4}

Test 5: {score5}

Test 6: {score6}

Thanks again from all of our research team.


Seb""".format(**score_dict)`

对于CSV文件的每一行,score_dict将类似于{score1:7, score2:9, ...}

P.S .:您也可以通过string模块中包含的某些方法,使用$ placeholders进行类似的操作,但是我认为这是一种osbolete。顺便说一下,使用多行字符串(带有三引号),您无需显式包括换行符(除非您使用r"""my string"""之类的“原始字符串”),而只需留空行即可。

编辑

假设您有4个称为score1,score2,score3,score4的分数,然后为每一行(https://docs.python.org/3/library/csv.html#index-3)(cfr。{{3}})执行此操作。

name,score1,score2,score3,score4=[col for col in row.split(';') if col!='']

if col!=''部分负责尾随的;