一个简单模版系统的实现:

# 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

运行程序:

 

posted on 2013-04-19 11:46  101010  阅读(394)  评论(0编辑  收藏  举报