替换文本temp中的变量

2024-06-12 01:13:30 发布

您现在位置:Python中文网/ 问答频道 /正文

所以我的文本文件是这样写的:

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”

^{pr2}$

Tags: andofnameintestyouyourthat
1条回答
网友
1楼 · 发布于 2024-06-12 01:13:30

创建一个“模板”,然后使用字典中存储的值填充占位符{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, ...}。在

注:您也可以通过string模块中包含的某种方法对$placeholders执行类似的操作,但我认为这是一种渗透。顺便说一句,使用多行字符串(带三个引号)您不需要显式地包含新行(除非您使用“raw strings”,如r"""my string"""),只需留下一个空行。在

编辑

假设你有4个分数叫做score1,score2,score3,score4然后(cfr。https://docs.python.org/3/library/csv.html#index-3)对每一行执行此操作。在

^{pr2}$

if col!=''部分处理尾随的;(如果有)。在

相关问题 更多 >