#templates.py import fileinput, re field_pat = re.compile(r'\[(.*?)\]') scope = {} 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) print field_pat.sub(replacement, text)现在编辑两个文件,通过调用这个脚本来处理: cat > magnus.txt [name = 'Magnus Lie Hetland' ] [email = 'magnus@foo.bar' ] [language = 'python' ] cat > template.txt [import time] Dear [name]. I would like to learn how to program. I hear you use the [language] a lot. Please help me to learn Oscar 现在来调用: python templates.py magnus.txt template.txt 结果: Dear Magnus Lie Hetland. I would li䪥 to learn how to program. I hear you use the python a lot. Please help me to learn Oscar templates.py脚本把template.txt中[]定义的变量替换成了magnus.txt中定义好的值。
3 回答
慕丝7291255
TA贡献1859条经验 获得超6个赞
读入两个文件之后用正则表达式匹配方括号,eval执行方括号内的内容,所以 magnus.txt就给name等变量赋值,sub的作用则是将正则表达式匹配出的内容(包括方括号)替换为eval语句的返回值。赋值语句的返回值是None,所以magnus.txt全部被替换掉,template.txt中的变量替换为前面赋值过的变量值。
简答说就是,把方括号和里面的内容替换成方括号里的内容作为Python语句的返回值
- 3 回答
- 0 关注
- 460 浏览
添加回答
举报
0/150
提交
取消