blob: cf4e17c1fc862c585ffd0fdea497d34974bdf7c6 [file] [log] [blame]
Guido van Rossuma8b37ad1999-08-19 16:00:41 +00001#!/usr/local/bin/python
2""" Utility for parsing HTML entity definitions available from:
3
4 http://www.w3.org/ as e.g.
5 http://www.w3.org/TR/REC-html40/HTMLlat1.ent
6
7 Input is read from stdin, output is written to stdout in form of a
8 Python snippet defining a dictionary "entitydefs" mapping literal
9 entity name to character or numeric entity.
10
Tim Peters70c43782001-01-17 08:48:39 +000011 Marc-Andre Lemburg, mal@lemburg.com, 1999.
Guido van Rossuma8b37ad1999-08-19 16:00:41 +000012 Use as you like. NO WARRANTIES.
13
14"""
15import re,sys
16import TextTools
17
18entityRE = re.compile('<!ENTITY +(\w+) +CDATA +"([^"]+)" +-- +((?:.|\n)+?) *-->')
19
20def parse(text,pos=0,endpos=None):
21
22 pos = 0
23 if endpos is None:
Jeremy Hylton0b7b4b82000-09-18 01:46:01 +000024 endpos = len(text)
Guido van Rossuma8b37ad1999-08-19 16:00:41 +000025 d = {}
26 while 1:
Jeremy Hylton0b7b4b82000-09-18 01:46:01 +000027 m = entityRE.search(text,pos,endpos)
28 if not m:
29 break
30 name,charcode,comment = m.groups()
31 d[name] = charcode,comment
32 pos = m.end()
Guido van Rossuma8b37ad1999-08-19 16:00:41 +000033 return d
34
35def writefile(f,defs):
36
37 f.write("entitydefs = {\n")
38 items = defs.items()
39 items.sort()
40 for name,(charcode,comment) in items:
Jeremy Hylton0b7b4b82000-09-18 01:46:01 +000041 if charcode[:2] == '&#':
42 code = int(charcode[2:-1])
43 if code < 256:
44 charcode = "'\%o'" % code
45 else:
46 charcode = repr(charcode)
47 else:
48 charcode = repr(charcode)
49 comment = TextTools.collapse(comment)
50 f.write(" '%s':\t%s, \t# %s\n" % (name,charcode,comment))
Guido van Rossuma8b37ad1999-08-19 16:00:41 +000051 f.write('\n}\n')
52
53if __name__ == '__main__':
54 if len(sys.argv) > 1:
Jeremy Hylton0b7b4b82000-09-18 01:46:01 +000055 infile = open(sys.argv[1])
Guido van Rossuma8b37ad1999-08-19 16:00:41 +000056 else:
Jeremy Hylton0b7b4b82000-09-18 01:46:01 +000057 infile = sys.stdin
Guido van Rossuma8b37ad1999-08-19 16:00:41 +000058 if len(sys.argv) > 2:
Jeremy Hylton0b7b4b82000-09-18 01:46:01 +000059 outfile = open(sys.argv[2],'w')
Guido van Rossuma8b37ad1999-08-19 16:00:41 +000060 else:
Jeremy Hylton0b7b4b82000-09-18 01:46:01 +000061 outfile = sys.stdout
Guido van Rossuma8b37ad1999-08-19 16:00:41 +000062 text = infile.read()
63 defs = parse(text)
64 writefile(outfile,defs)