functional programming with map()
Donnal Walter
donnal at donnal.net
Wed Feb 27 21:45:59 EST 2002
I wish to thank everyone that contributed to this thread. I have
been overwhelmed at the response, but this discussion has been
extremely helpful. Thank you
As a result, I attached a dozen lines of code to my XML database
management module so that I can now generate sophistocated reports
from an HTML template with embedded string formatting operators (%) .
These refer to an embedded dictionary at the end of the HTML file
something like this:
<html>
<head><title>Prism: Progress Note</title></head>
<body>
<table width="100%%" cellpadding="5"><tr>
<td width="70" valign="top"><p>%(date)s</p></td>
<td>
<p><strong>Assessment and Plan:</strong></p>
<ol>
<li>%(ga)s wk newborn infant %(order)s, birthweight %(bw)s kg,
yesterday %(wt)s kg,<br />
chronologic age %(age)s, post-conceptual age %(pca)s wk. <br />
</li>
<li>Temperature control: %(heat)s
</li>
<li>Respiratory support: %(resp)s <br />
</li>
<li>Nutrition and Fluids:<br /> %(fen)s <br />
</li>
%(pList)s
</ol><br /><br />
<br /><br /><br />_______________________________________<br />
Donnal Walter, M.D., Attending Neonatologist
</td>
</tr></table>
<!-- <vars>{
'date': self.today.GetDate(),
'ga': self.birthGA.Get(),
'order': self.birthorder.Get(),
'bw': self.birthweight.Get(),
'wt': self.weight.Get(),
'age': self.age.Get(),
'pca': self.pca.Get(),
'heat': self.warmer.Get(),
'resp': self.respiratory.Get(),
'fen': (
IF(self.formula.Get(),
('____ cc/kg/day enteral of ' +
self.formula.Get() + '<br />'),
'') +
'____ cc/kg/day total fluids, ____ kcal/kg/day' +
'<br /> ____ cc/kg/hr urine output;' +
IF(self.lytes.Get(),
'<br />Na____, K____, Cl____, CO____,',
'')
),
'pList': CONCAT([('<li>' + x.label.Get() +
IF(len(x.meds),
('<ul>' +
CONCAT([('<li>' + y.label.Get() +
IF(y.dose.Get(),
(', ' +
y.dose.Get() + ' ' +
y.units.Get() + ' (' +
y.scaled.Get() + ' ' +
y.units.Get() + '/kg) ' +
y.route.Get() + ' every ' +
y.interval.Get() + ' hr; '),
'') +
'</li>'
) for y in x.meds]) +
'</ul>' ),
'') +
'</li>'
) for x in self.problems])
}</vars>
-->
</body></html>
Note especially the loops in the definition for pList (problem list).
The code that interprets this template is simply:
def Generate(self, filename):
"""filename = template file"""
IF = lambda a,b,c:(a and [b] or [c])[0]
CONCAT = lambda z:reduce((lambda x,y: x+y), z, ' ')
try: # try this
io = open(filename, 'r') # open read only
t = io.read() # read full text
io.close() # close file
i = string.find(t, '<vars>') # start of vars
j = string.find(t, '</vars>') # end of vars
s = t[:i] + t[j+7:] # remove "vars"
v = eval(t[i+6:j]) # make dictionary
return s % v # return string
except KeyError: # unless key error
return 'Key error in template' # then warning
def Write(self, template, output):
io = open(output, 'w')
io.write(self.Generate(template))
io.close()
Thanks again,
Donnal Walter
More information about the Python-list
mailing list