Feb
5
#!/usr/bin/python
"""
py2html
Prepare a python script for posting on a wordpress blog
USAGE:
py2html <mypython.py >myhtml.html
"""
import sys,re
mapping=[
('&','&'),
("'",'''),
(' ',' '),
('"','"'),
('<','<'),
('>','>')
]
print '<PRE>'
for l in sys.stdin:
for (fro,to) in mapping:
l=l.replace(fro, to)
l=l.strip()
print '%s<BR />'%l
print '</PRE>'
(I only posted that so I could have the pleasure of running a program with itself as input)
/edit: I just re-did the other listing with http://tom.idealog.info/blog/20031205-1070600658.shtml … though I needed to re-do the “quote” function in there to use the “mapping” from above.
#!/usr/bin/python """ yield.py Demonstrates a recursive generator method. This allows very large nested Container structures to be created, and when rendering to a string, we don't need to create the whole thing in memory (handy if, like me, you want to create 160,000 line XML files. """ class Container(object): def __init__(self, name, contents=[]): self.tag=name self.contents=contents def lines(self): """ Iterate over the text representing the Container and its contents. """ # This is a generator function; really it returns an iterable object. The # only reason you know this is that it contains the yield statement. On # one hand, a nasty gotcha for the rookie pythoneer, on the other hand, a # lovely concise way of doing something you will want to do often. yield "<%s>"%(self.tag.upper()) if isinstance(self.contents, str): yield self.contents else: for x in self.contents: if isinstance(x,Container): for l in x.lines(): yield l else: yield x yield "</%s>"%self.tag # Declare a structure of nested Container objects c=Container('HTML', [ Container('HEAD', [ Container('TITLE',[ "The quick and the Dead" ]) ]), Container('BODY', [ "The quick, that's me, and the dead, that's you.", Container('Blockquote', "Ar wuz never wun te be hackin' about this here county") ]), ]) # Now write the structure's text representation out. for l in c.lines(): print "Line: %s"%l