一个简单的模版系统
2013-04-19 11:46
162 查看
一个简单模版系统的实现:
简单模版示例:
运行程序:
修改替换函数replacement中的return ''为return 'test black line',运行结果:
这样可以清楚的看出,以上的输出,包含了3个空行,其中2个在输出文本的上方,一个在输出文本的下方。上方的2行是执行exec时返回的,下方的一行是print语句输出打印语句后默认的换行。
因为使用了fileinput,所以可以轮流处理几个文件。这意味着可以使用一个文件用于定义变量值(文件名为define.txt),另一个文件用于插入这些值的模版文件(template.txt)。
(1)模版的定义
(2)模版文件
运行程序:
# 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, scope) # 返回空字符串 return '' # 将所有文本以一个字符串的形式获取 lines = [] for line in fileinput.input(): lines.append(line) text = ''.join(lines) # print(text) # 将field_pat模式的所有匹配项都用替换函数replacement替换掉 print(field_pat.sub(replacement, text))
简单模版示例:
[x = 2] [y = 3] the sum of [x] and [y] id [x + y]
运行程序:
修改替换函数replacement中的return ''为return 'test black line',运行结果:
这样可以清楚的看出,以上的输出,包含了3个空行,其中2个在输出文本的上方,一个在输出文本的下方。上方的2行是执行exec时返回的,下方的一行是print语句输出打印语句后默认的换行。
因为使用了fileinput,所以可以轮流处理几个文件。这意味着可以使用一个文件用于定义变量值(文件名为define.txt),另一个文件用于插入这些值的模版文件(template.txt)。
(1)模版的定义
[name = 'huhu'] [language = 'python'] [email = 'huhu@163.com']
(2)模版文件
[import time] hello,[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? hangzhou. [time.asctime()] hengheng
运行程序:
相关文章推荐
- 简单的搭建一个高并发低时延系统
- 一个简单的卡动车排队系统
- 一个简单漂亮的Java博客系统
- 一个简单的酒店系统的数据库设计
- 一个简单的网上报名系统【1】
- 用redis 做一个简单的 pub / sub 系统
- 【Linux学习】 写一个简单的Makefile编译源码获取当前系统时间
- 一个系统从登陆到数据库交互的简单实现(java)
- 一个简单的论坛系统
- 为LINUX 设计一个简单的二级文件系统。
- 深入浅出linux之如何打开文件2(写一个最简单文件系统) .
- win10为什么这么火? 简单评论一下Windows 10是一个什么样的系统
- 一个简单的第三人称汽车驾驶系统
- 基于JAVA集合框架实现一个简单的学生管理系统
- 实现一个简单的语音聊天室(多人语音聊天系统)
- Linux内核分析(三)内核启动过程分析——构造一个简单的Linux系统
- 一个简单的自动发送邮件系统(三)
- Qt:使用gSoap做一个简单的CS系统
- 一个简单系统调用用例分析
- 在kaldi工具包使用小数字语料库创建一个简单的ASR系统(番外篇)