~dustin-spy/twisted/dustin

« back to all changes in this revision

Viewing changes to admin/sgmlfilter.py

  • Committer: carmstro
  • Date: 2002-03-16 22:54:55 UTC
  • Revision ID: vcs-imports@canonical.com-20020316225455-53a8cf46dc4267e2
new doc-generator, admin/ directory, class renamings, slight doc update.

Show diffs side-by-side

added added

removed removed

Lines of Context:
 
1
#Stolen from _Python Standard Library_, by Fredrik Lundh, chapter 5.
 
2
 
 
3
import sgmllib
 
4
import cgi, string, sys
 
5
 
 
6
class SGMLFilter(sgmllib.SGMLParser):
 
7
    # sgml filter.  override start/end to manipulate
 
8
    # document elements
 
9
 
 
10
    def __init__(self, outfile=None, infile=None):
 
11
        sgmllib.SGMLParser.__init__(self)
 
12
        if not outfile:
 
13
            outfile = sys.stdout
 
14
        self.write = outfile.write
 
15
        if infile:
 
16
            self.load(infile)
 
17
 
 
18
    def load(self, file):
 
19
        while 1:
 
20
            s = file.read(8192)
 
21
            if not s:
 
22
                break
 
23
            self.feed(s)
 
24
        self.close()
 
25
 
 
26
    def handle_entityref(self, name):
 
27
        self.write("&%s;" % name)
 
28
 
 
29
    def handle_data(self, data):
 
30
        self.write(cgi.escape(data))
 
31
 
 
32
    def unknown_starttag(self, tag, attrs):
 
33
        tag, attrs = self.start(tag, attrs)
 
34
        if tag:
 
35
            if not attrs:
 
36
                self.write("<%s>" % tag)
 
37
            else:
 
38
                self.write("<%s" % tag)
 
39
                for k, v in attrs:
 
40
                    self.write(" %s=%s" % (k, repr(v)))
 
41
                self.write(">")
 
42
 
 
43
    def unknown_endtag(self, tag):
 
44
        tag = self.end(tag)
 
45
        if tag:
 
46
            self.write("</%s>" % tag)
 
47
 
 
48
    def start(self, tag, attrs):
 
49
        return tag, attrs # override
 
50
 
 
51
    def end(self, tag):
 
52
        return tag # override
 
53