q2 = """
Michael
dawn
lock hart ln
Dublin
--
kate
Nan
webster st
king city
--
raj
zakjg
late Road
Toronto
--
dave
porter
Rock Ave
nobleton
--
John
Doe
round road
schomberg
"""
letter = """
[fname] [lname]
[street]
[city]
Dear [fname]:
As a fellow citizen of [city], you and all your neighbours
on [street] are invited to a celebration this Saturday at
[city]'s Central Park. Bring beer and food!
"""
with open('q2.txt', 'w') as f:
f.write(q2)
f.close()
with open('letter.txt', 'w') as f:
f.write(letter)
f.close()
letter = ''
q2 = ''
with open('letter.txt', 'r') as f:
letter = f.read()
f.close()
with open('q2.txt', 'r') as f:
q2 = f.read()
f.close()
q2
'\nMichael\n\ndawn\n\nlock hart ln\n\nDublin\n\n--\n\nkate\n\nNan\n\nwebster st\n\nking city\n\n--\n\nraj\n\nzakjg\n\nlate Road\n\nToronto\n\n--\n\ndave\n\nporter\n\nRock Ave\n\nnobleton\n\n--\n\nJohn\n\nDoe\n\nround road\n\nschomberg\n'
letter
"\n[fname] [lname]\n[street]\n[city]\n\nDear [fname]:\n\n As a fellow citizen of [city], you and all your neighbours \non [street] are invited to a celebration this Saturday at \n[city]'s Central Park. Bring beer and food!\n"
def cleanData(query):
return [item.strip().split('\n\n') for item in query.split('--')]
def writeLetter(template, variables, replacements):
# replace ith variable with ith replacement variable
for i in range(len(variables)):
template = template.replace(variables[i], replacements[i])
return template
data = cleanData(q2)
data
[['Michael', 'dawn', 'lock hart ln', 'Dublin'], ['kate', 'Nan', 'webster st', 'king city'], ['raj', 'zakjg', 'late Road', 'Toronto'], ['dave', 'porter', 'Rock Ave', 'nobleton'], ['John', 'Doe', 'round road', 'schomberg']]
variables = ['[fname]', '[lname]', '[street]', '[city]']
letters = [writeLetter(letter, variables, person) for person in data]
for i in letters:
print i
Michael dawn lock hart ln Dublin Dear Michael: As a fellow citizen of Dublin, you and all your neighbours on lock hart ln are invited to a celebration this Saturday at Dublin's Central Park. Bring beer and food! kate Nan webster st king city Dear kate: As a fellow citizen of king city, you and all your neighbours on webster st are invited to a celebration this Saturday at king city's Central Park. Bring beer and food! raj zakjg late Road Toronto Dear raj: As a fellow citizen of Toronto, you and all your neighbours on late Road are invited to a celebration this Saturday at Toronto's Central Park. Bring beer and food! dave porter Rock Ave nobleton Dear dave: As a fellow citizen of nobleton, you and all your neighbours on Rock Ave are invited to a celebration this Saturday at nobleton's Central Park. Bring beer and food! John Doe round road schomberg Dear John: As a fellow citizen of schomberg, you and all your neighbours on round road are invited to a celebration this Saturday at schomberg's Central Park. Bring beer and food!