Заменить переменные в текстовом шаблоне - PullRequest
0 голосов
/ 25 октября 2018

Итак, мой текстовый файл говорит что-то вроде этого:

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: объект «список» имеетбез атрибута '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 голосов
/ 25 октября 2018

Создайте «шаблон», затем заполните заполнители {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, ...}.

PS: вы также можете сделать что-то подобное с заполнителями $ с помощью какого-либо метода, включенного в модуль string, но я думаю, что это немного устарело.Кстати, при использовании многострочных строк (с тремя кавычками) вам не нужно явно включать новые строки (если вы не используете «необработанные строки», такие как r"""my string"""), просто оставляйте пустую строку.

EDIT

Предполагая, что у вас есть 4 балла, называемых «Score1, Score2, Score3, Score4 затем» (ср. https://docs.python.org/3/library/csv.html#index-3) для каждой строки, выполните это.

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

Часть if col!='' заботится отрейлинг ; если есть.

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...