python 简单的模板系统

2019-09-24  本文已影响0人  zenos876

背景

# 'the sum of 7 and 9 is [7 + 9]' - > 'the sum of 7 and 9 is 16'
# '[name="Mr.zenos"]hello, [name]' -> 'hello, Mr.zenos'

1. 使用正则表达式获取内容
2. 使用eval计算表达式字符串, 执行操作, 如果产生异常就是语句
3. 使用exec执行语句字符串
4. 使用re.sub执行语句替换字符串
template.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, scope)
        return ''
    
lines = []
for line in fileinput.input():
    lines.append(line)
text = ''.join(lines)

print(field_pat.sub(replacement, text))

template.txt

[name="Mr.zenos"]
'the sum of 7 and 9 is [7 + 9]'
'hello, [name]'

运行结果

python -u "c:\Users\87600\Desktop\python_basic_learning\10.module\test_template.py" "c:\Users\87600\Desktop\python_basic_learning\10.module\template.txt"

'the sum of 7 and 9 is 16'
'hello, Mr.zenos'
上一篇 下一篇

猜你喜欢

热点阅读