blob: a042d1c24cc1de90486aa16fb93fa753c01d4a63 [file] [log] [blame]
Benjamin Peterson90f5ba52010-03-11 22:53:45 +00001#!/usr/bin/env python3
Guido van Rossuma8b37ad1999-08-19 16:00:41 +00002""" 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
Guido van Rossuma8b37ad1999-08-19 16:00:41 +000016
17entityRE = re.compile('<!ENTITY +(\w+) +CDATA +"([^"]+)" +-- +((?:.|\n)+?) *-->')
18
19def parse(text,pos=0,endpos=None):
20
21 pos = 0
22 if endpos is None:
Jeremy Hylton0b7b4b82000-09-18 01:46:01 +000023 endpos = len(text)
Guido van Rossuma8b37ad1999-08-19 16:00:41 +000024 d = {}
25 while 1:
Jeremy Hylton0b7b4b82000-09-18 01:46:01 +000026 m = entityRE.search(text,pos,endpos)
27 if not m:
28 break
29 name,charcode,comment = m.groups()
30 d[name] = charcode,comment
31 pos = m.end()
Guido van Rossuma8b37ad1999-08-19 16:00:41 +000032 return d
33
34def writefile(f,defs):
35
36 f.write("entitydefs = {\n")
Georg Brandl8efadf52008-05-16 15:23:30 +000037 items = sorted(defs.items())
38 for name, (charcode,comment) in items:
Jeremy Hylton0b7b4b82000-09-18 01:46:01 +000039 if charcode[:2] == '&#':
40 code = int(charcode[2:-1])
41 if code < 256:
42 charcode = "'\%o'" % code
43 else:
44 charcode = repr(charcode)
45 else:
46 charcode = repr(charcode)
R David Murray54ac8322012-04-04 21:28:14 -040047 comment = ' '.join(comment.split())
Jeremy Hylton0b7b4b82000-09-18 01:46:01 +000048 f.write(" '%s':\t%s, \t# %s\n" % (name,charcode,comment))
Guido van Rossuma8b37ad1999-08-19 16:00:41 +000049 f.write('\n}\n')
50
51if __name__ == '__main__':
52 if len(sys.argv) > 1:
Jeremy Hylton0b7b4b82000-09-18 01:46:01 +000053 infile = open(sys.argv[1])
Guido van Rossuma8b37ad1999-08-19 16:00:41 +000054 else:
Jeremy Hylton0b7b4b82000-09-18 01:46:01 +000055 infile = sys.stdin
Guido van Rossuma8b37ad1999-08-19 16:00:41 +000056 if len(sys.argv) > 2:
Jeremy Hylton0b7b4b82000-09-18 01:46:01 +000057 outfile = open(sys.argv[2],'w')
Guido van Rossuma8b37ad1999-08-19 16:00:41 +000058 else:
Jeremy Hylton0b7b4b82000-09-18 01:46:01 +000059 outfile = sys.stdout
Guido van Rossuma8b37ad1999-08-19 16:00:41 +000060 text = infile.read()
61 defs = parse(text)
62 writefile(outfile,defs)