#templates.py import fileinput,re #匹配中括号里的字段 field_pat=re.compile(r'/[(.+?)/]') #将变量收集到这里 scope={} #用于re.sub中 def replacement(match): code=match.group(1) try: #如果字段可以求值,返回它 return str(eval(code,scope)) except SyntaxError: # 否则执行相同作用域内的赋值语句 exec code in scope #... ...返回空字符串 return '' #将所有文本以一个字符串的形式获取: lines=[] for line in fileinput.input(): lines.append(line) text=''.join(lines) #将field模式的所有匹配项都替换掉: print text print field_pat.sub(replacement,text)
测试文件:magnu.txt,template.txt
[name = 'Magnus Lie Hetland' ] [email = 'magnus@foo.bar' ] [language = 'python' ]
[import time] Dear [name], I would like to learn how to program. I hear you use the [language] language a lot -- is it something I should consider? And, by the way, is [email] your correct email address? Fooville, [time.asctime()] Oscar Frozzbozz
运行程序:python templates.py magnus.txt template.txt
Result:
Dear Magnus Lie Hetland, I would like to learn how to program. I hear you use the python language a lot -- is it something I should consider? And, by the way, is magnus@foo.bar your correct email address? Fooville, Fri Mar 18 20:00:37 2011 Oscar Frozzbozz