|
[Original]
[Print]
[Top]
|
功能看test 函数内。
一时来劲,把这个功能的代码,重写几遍。最后就这样了:
#!/usr/bin/python
import re, string, sys
from StringIO import StringIO
keywords = 'end', 'template', 'if', 'elif', 'else', 'apply-template', 'include'
_varname = re.compile('${(w+)}')
_meta = re.compile('^s*<!--s*#s*(%s)(.*)-->s*$' % '|'.join(keywords))
def _G_repl(txt, dct):
return re.sub(_varname, lambda g: str(dct.get(g.group(1))), txt)
def _G_meta(line):
if line.lstrip()[:4] == '<!--':
res = re.search(_meta, line)
if res:
return res.group(1, 2)
return 0, 0
class thtml:
def __init__(self, src):
self._src = src
def begin(self, dct):
line = self._src.readline()
while line:
if self.recv(line, dct) == 0:
break
line = self._src.readline()
def recv(self, line, dct):
key, exp = _G_meta(line)
if key:
return self.statement(key, exp, dct)
return self.normal(line, dct)
def statement(self, key, exp, dct):
assert key in ('if', 'template', 'apply-template', 'include')
if key == 'if':
exp = eval(_G_repl(exp[:exp.rindex(':')], dct))
tif(self._src, exp).begin(dct)
elif key == 'template':
exp = eval(_G_repl(exp[:exp.rindex(':')], dct))
txt = []
textract(self._src, txt).begin(dct)
txt.pop()
_templates[exp] = StringIO(''.join(txt))
elif key == 'include':
exp = eval(_G_repl(exp, dct))
xf = file(exp)
thtml(xf).begin(dct)
elif key == 'apply-template':
exp = eval(_G_repl(exp, dct))
xf = _templates[exp]
for d in _dicts[exp]:
thtml(xf).begin(d)
xf.seek(0)
return 1
def normal(self, line, dct):
sys.stdout.write(_G_repl(line, dct))
return 1
class tskip(thtml):
def __init__(self, src):
thtml.__init__(self, src)
def statement(self, key, exp, dct):
if key == 'end':
return 0
elif key in ('if', 'template'):
tskip(self._src).begin(dct)
return 1
def normal(self, line, dct):
return 1
class textract(thtml):
def __init__(self, src, lines):
thtml.__init__(self, src)
self._lines = lines
def recv(self, line, dct):
self._lines.append(line)
return thtml.recv(self, line, dct)
def statement(self, key, exp, dct):
if key == 'end':
return 0
elif key in ('if', 'template'):
textract(self._src, self._lines).begin(dct)
return 1
def normal(self, line, dct):
return 1
class tif(thtml):
def __init__(self, src, bool):
thtml.__init__(self, src)
self._true = bool
def statement(self, key, exp, dct):
if key == 'end':
return 0
elif key in ('elif', 'else'):
if self._true:
tskip(self._src).begin(dct)
else:
if key == 'elif':
self._true = eval(_G_repl((exp[: exp.rindex(':')]), dct))
else:
self._true = 1
else:
if self._true:
return thtml.statement(self, key, exp, dct)
elif key in ('if', 'template'):
tskip(self._src).begin(dct)
return 1
def normal(self, line, dct):
if self._true:
thtml.normal(self, line, dct)
_dicts = {}
_templates = {}
def printf(xf, glob, **tmps):
for k, v in tmps.items():
if type(v) == dict:
_dicts[k] = [v]
elif type(v) == list:
_dicts[k] = v
if type(xf) == string:
thtml(file(xf)).begin(glob)
else:
thtml(xf).begin(glob)
def xprintf(xf, root = {'x':1, 'tpl':[{},{}]}):
pass
def test():
input = StringIO("""
<!-- #template 'foo': -->
<li>${foo}</li>
<li>${bar}</li>
<!-- #end -->
<!-- #template 'bar': -->
<!-- #include 'inc.html' -->
<!-- #end -->
<html><body>
<!-- #apply-template 'bar' -->
<!-- #if '${select}' == '*if*': -->
<h2>${select} in '#if'</h2>
<!-- #apply-template 'foo' -->
<!-- #elif '${select}' == '*elif*': -->
<h2>${select} in '#elif'</h2>
<!-- #if '${select}' == '*elif*': -->
<h2>${select} in '#elif/#elif'</h2>
<!-- #apply-template 'foo' -->
<!-- #end: -->
<!-- #else: -->
<h2>${select} in '#else'</h2>
<!-- #apply-template 'foo' -->
<!-- #end -->
</body></html>
""")
glob = {}
glob['select'] = '*elif*'
glob['if'] = '*if*'
glob['elif'] = '*elif*'
glob['else'] = '*else*'
foo = {'foo':'*foo*', 'bar':'*bar*'}
bar = []
bar.append(foo)
bar.append({'foo':'*foo foo*', 'bar':'*bar bar*'})
printf(input, glob, foo=foo, bar=bar)
if __name__ == '__main__':
test()
|
|
|
----
温故知新
|
|
[Original]
[Print]
[Top]
|
|
[Original]
[Print]
[Top]
|
#! /usr/bin/python
import re, string, sys
keywords = 'end', 'template', 'if', 'elif', 'else', 'apply-template', 'include'
_varname = re.compile('${(w+)}')
_meta = re.compile('^s*<!--s*#s*(%s)(.*)-->s*$' % '|'.join(keywords))
_templates = {}
class THtml:
def __init__(self, src):
self._liter = src
def begin(self, dct):
try:
while self.recv(self._liter.next(), dct) == 1: pass
except:
pass
return self._liter
def recv(self, line, dct):
key, exp = _G_meta(line)
if key:
return self.statement(key, exp, dct)
return self.normal(line, dct)
def statement(self, key, exp, dct):
assert key in ('if', 'template', 'apply-template', 'include')
if key == 'if':
exp = eval(_G_repl(exp[:exp.rindex(':')], dct))
self._liter = If(exp, self._liter).begin(dct)
elif key == 'template':
exp = eval(_G_repl(exp[:exp.rindex(':')], dct))
txt = []
self._liter = Extract(self._liter, txt).begin(dct)
txt.pop()
_templates[exp] = txt
elif key == 'include':
exp = eval(_G_repl(exp, dct))
THtml(file(exp).readlines()).begin(dct)
elif key == 'apply-template':
exp = eval(_G_repl(exp, dct))
for d in dct[exp]:
vf = iter(_templates[exp])
THtml(vf).begin(d)
return 1
def normal(self, line, dct):
sys.stdout.write(_G_repl(line, dct))
return 1
class Skip(THtml):
def __init__(self, src):
THtml.__init__(self, src)
def statement(self, key, exp, dct):
if key == 'end':
return 0
elif key in ('if', 'template'):
self._liter = Skip(self._liter).begin(dct)
return 1
def normal(self, line, dct):
return 1
class Extract(THtml):
def __init__(self, src, lines):
THtml.__init__(self, src)
self._lines = lines
def recv(self, line, dct):
self._lines.append(line)
return THtml.recv(self, line, dct)
def statement(self, key, exp, dct):
if key == 'end':
return 0
elif key in ('if', 'template'):
self._liter = Extract(self._liter, self._lines).begin(dct)
return 1
def normal(self, line, dct):
return 1
class If(THtml):
def __init__(self, bool, src):
THtml.__init__(self, src)
self._true = bool
def statement(self, key, exp, dct):
if key == 'end':
return 0
elif key in ('elif', 'else'):
if self._true:
self._liter = Skip(self._liter).begin(dct)
else:
if key == 'elif':
self._true = eval(_G_repl((exp[: exp.rindex(':')]), dct))
else:
self._true = 1
else:
if self._true:
return THtml.statement(self, key, exp, dct)
elif key in ('if', 'template'):
self._liter = Skip(self._liter).begin(dct)
return 1
def normal(self, line, dct):
if self._true:
THtml.normal(self, line, dct)
return 1
def _G_repl(txt, dct):
return re.sub(_varname, lambda g: str(dct.get(g.group(1))), txt)
def _G_meta(line):
if line.lstrip()[:4] == '<!--':
res = re.search(_meta, line)
if res:
return res.group(1, 2)
return 0, 0
def fprintf(outf, filename, glob):
bak, sys.stdout = sys.stdout, outf
printf(filename, glob)
sys.stdout = bak
def printf(filename, glob):
if type(filename) == str:
THtml(iter(file(filename).readlines())).begin(glob)
else:
THtml(iter(filename)).begin(glob)
def test():
from StringIO import StringIO
content = """<?xml version = "1.0"?>
<?xml:stylesheet type = "text/xsl" href = "xszt.xsl"?>
<!-- #template 'glob': -->
<number1>
<name>${name}</name>
<gender>${sex}</gender>
<age>${age}</age>
<result_exam>
<!-- #template 'result_exam': -->
<subject>${subject}</subject>
<score>${score}</score>
<!-- #end -->
<!-- #apply-template 'result_exam' -->
</result_exam>
<family>
<!-- #template 'family': -->
<name>${name}</name>
<age>${age}</age>
<!-- #end -->
<!-- #apply-template 'family' -->
</family>
<city>${city}</city>
</number1>
<!-- #end -->
<xueshengzhuangtai>
<!-- #apply-template 'glob' -->
</xueshengzhuangtai>
<!-- #include 'draft-gg-udt-01.txt' -->
"""
def test_data():
data = """Xiaoyu * female * 20 * english 80 maths 88 chinese 92 * song 44 yang 45 *
Beijing *
wu * male * 20 * c/c++ 8 maths 8 listening 9 * wu 4 wu 4 * ShenZhen * """
glob = []
for line in data.splitlines():
h = {}
v = [x.strip() for x in line.rstrip().split('*')][:-1]
h['name'], h['sex'], h['age'], result_exam, family, h['city'] = v
h['result_exam'] = []
h['family'] = []
if result_exam:
r = result_exam.split()
while r:
t = {}
t['score'], t['subject'] = r.pop(), r.pop()
h['result_exam'].append(t)
if family:
r = family.split()
while r:
t = {}
t['age'], t['name'] = r.pop(), r.pop()
h['family'].append(t)
glob.append(h)
return glob
glob = test_data()
fprintf(sys.stderr, StringIO(content).readlines(), { 'glob' : glob })
if __name__ == '__main__':
test()
|
|
|
----
温故知新
|
|
[Original]
[Print]
[Top]
|
|
[Original]
[Print]
[Top]
|
#! /usr/bin/python
import re, sys
keywords = 'end', 'template', 'if', 'elif', 'else', 'apply-template', 'include'
_varname = re.compile('%{(w+)}')
_meta = re.compile('^s*<!--s*#s*(%s)(.*)-->s*$' % '|'.join(keywords))
_templates = {}
class THtml:
def __init__(self, src):
self._liter = iter(src)
def begin(self, dct):
try:
while self.recv(self._liter.next(), dct): pass
except StopIteration:
pass
return self._liter
def recv(self, line, dct):
key, exp = _G_meta(line)
if key:
return self.statement(key, exp, dct)
return self.normal(line, dct)
def statement(self, key, exp, dct):
if key == 'if':
exp = eval(_G_repl(exp[:exp.rindex(':')], dct))
self._liter = If(exp, self._liter).begin(dct)
elif key == 'template':
exp = eval(_G_repl(exp[:exp.rindex(':')], dct))
txt = []
self._liter = Extract(self._liter, txt).begin(dct)
txt.pop()
_templates[exp] = txt
elif key == 'include':
exp = eval(_G_repl(exp, dct))
THtml(file(exp).readlines()).begin(dct)
elif key == 'apply-template':
exp = eval(_G_repl(exp, dct))
tval = dct.get(exp, {})
if type(tval) == list:
for d in tval:
THtml(_templates.get(exp, [])).begin(d)
elif type(tval) == dict:
THtml(_templates.get(exp, [])).begin(tval)
elif tval != None:
raise ValueError, "'%s': type of '{}/[{}*]' expected" % exp
else: assert 0, 'Unknown keyword: ' + key
return 1
def normal(self, line, dct):
sys.stdout.write(_G_repl(line, dct))
return 1
class Skip(THtml):
def __init__(self, src):
THtml.__init__(self, src)
def statement(self, key, exp, dct):
if key == 'end':
return 0
elif key in ('if', 'template'):
self._liter = Skip(self._liter).begin(dct)
return 1
def normal(self, line, dct):
return 1
class Extract(THtml):
def __init__(self, src, lines):
THtml.__init__(self, src)
self._lines = lines
def recv(self, line, dct):
self._lines.append(line)
return THtml.recv(self, line, dct)
def statement(self, key, exp, dct):
if key == 'end':
return 0
elif key in ('if', 'template'):
self._liter = Extract(self._liter, self._lines).begin(dct)
return 1
def normal(self, line, dct):
return 1
class If(THtml):
def __init__(self, bool, src):
THtml.__init__(self, src)
self._true = bool
def statement(self, key, exp, dct):
if key == 'end':
return 0
elif key in ('elif', 'else'):
if self._true:
self._liter = Skip(self._liter).begin(dct)
else:
if key == 'elif':
self._true = eval(_G_repl((exp[: exp.rindex(':')]), dct))
else:
self._true = 1
else:
if self._true:
return THtml.statement(self, key, exp, dct)
elif key in ('if', 'template'):
self._liter = Skip(self._liter).begin(dct)
return 1
def normal(self, line, dct):
if self._true:
THtml.normal(self, line, dct)
return 1
def _G_repl(txt, dct):
return re.sub(_varname, lambda g: str(dct.get(g.group(1))), txt)
def _G_meta(line):
res = re.search(_meta, line)
if res:
return res.group(1, 2)
return 0, 0
def fprintf(outf, filename, glob):
bak, sys.stdout = sys.stdout, outf
printf(filename, glob)
sys.stdout = bak
def printf(inf, glob):
if type(inf) == str:
inf = file(inf)
THtml(inf).begin(glob)
import os
def test():
from StringIO import StringIO
content = """
<?xml version = "1.0"?>
<?xml:stylesheet type = "text/xsl" href = "xszt.xsl"?>
<!-- #template 'glob': -->
<number1>
<name>%{name}</name>
<gender>%{sex}</gender>
<age>%{age}</age>
<result_exam>
<!-- #template 'result_exam': -->
<subject>%{subject}</subject>
<score>%{score}</score>
<!-- #end -->
<!-- #apply-template 'result_exam' -->
</result_exam>
<family>
<!-- #template 'family': -->
<!-- #if not os.path.exists('%{inc_file}'): -->
<name>%{name}</name>
<age>%{age}</age>
<!-- #else: -->
%{inc_file}
<!-- #include '%{inc_file}' -->
<!-- #end -->
<!-- #end -->
<!-- #apply-template 'family' -->
</family>
<city>%{city}</city>
</number1>
<!-- #end -->
<xueshengzhuangtai>
<!-- #apply-template 'glob' -->
</xueshengzhuangtai>
"""
def test_data():
data = """
Xiaoyu * female * 20 * english 80 maths 88 chinese 92 * song 44 yang 45 * Beijing *
()
wu * male * 20 * c/c++ 8 maths 8 listening 9 * wu 4 wei 5 * ShenZhen * ()
"""
glob = []
for line in data.splitlines():
h = {}
v = [x.strip() for x in line.rstrip().split('*')][:-1]
h['name'], h['sex'], h['age'], result_exam, family, h['city'] = v
h['result_exam'] = [{None: None}]
if result_exam:
r = result_exam.split()
while r:
t = {}
t['score'], t['subject'] = r.pop(), r.pop()
h['result_exam'].append(t)
h['family'] = []
if family:
r = family.split()
while r:
t = { 'inc_file' : 'family.inc' }
t['age'], t['name'] = r.pop(), r.pop()
h['family'].append(t)
glob.append(h)
return glob
glob = test_data()
try:
fprintf(sys.stdout, StringIO(content).readlines(), { 'glob' : glob })
except Exception, e:
print 'Error:', e
if __name__ == '__main__':
test()
|
|
|
----
温故知新
|
|
--
|
|
[Original]
[Print]
[Top]
|
|