#!/usr/bin/env python # coding: utf-8 # In[2]: 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! """ # In[4]: with open('q2.txt', 'w') as f: f.write(q2) f.close() with open('letter.txt', 'w') as f: f.write(letter) f.close() # In[5]: 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() # In[6]: q2 # In[7]: letter # In[8]: def cleanData(query): return [item.strip().split('\n\n') for item in query.split('--')] # In[9]: 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 # In[10]: data = cleanData(q2) # In[11]: data # In[12]: variables = ['[fname]', '[lname]', '[street]', '[city]'] # In[13]: letters = [writeLetter(letter, variables, person) for person in data] # In[14]: for i in letters: print i # In[ ]: # In[ ]: