Python代码请教

Stephenfzp 2016-07-19 02:10:52
#-*- coding:utf8 -*-

import fileinput , re

patt = re.compile(r'\[(.+?)\]')

scope = {}
def replace(match):
code = match.group(1)
try:
return str(eval(code , scope)) #若字段可以求值,则返回结果
except SyntaxError:
exec code in scope
return ''

lines = []
for line in fileinput.input('sum.txt'): #将文件所有文本以一个长的字符串形式获取
lines.append(line)
text = ''.join(lines)

print patt.sub(replace , text)


sum.txt:
[x=2]
[y=3]
sum of [x] and [y] is [x+y]

输出:
sum of 2 and 3 is 5

这是《Python基础教程》里面的一个例子——>简易实现一个模板系统 读取sum.txt里面的值再算出结果。
对于代码最后这句:print patt.sub(replace , text) 不是很懂。

我的理解是:先执行patt.sub()里面的replace()函数,执行完后再执行sub()函数。
问题:
1、求大神解释下patt.sub(replace , text)里面的replace怎么运行的??
2、定义的replace(match)的参数怎么传进的(因为我看到只是直接写了replece,所以不理解)??
3、后面用sub()函数替换所有匹配项,如果不是[x+y]就会返回‘ ‘,那不是应该输出sum of and is 5 吗??
...全文
182 1 打赏 收藏 转发到动态 举报
写回复
用AI写文章
1 条回复
切换为时间正序
请发表友善的回复…
发表回复
ming235cn 2016-07-19
  • 打赏
  • 举报
回复
patt = re.compile(r'\[(.+?)\]') print patt.sub(replace , text) 相当于resub(r'\[(.+?)\]', replace, text) 具体的可以去看看官方文档

37,737

社区成员

发帖
与我相关
我的任务
社区描述
JavaScript,VBScript,AngleScript,ActionScript,Shell,Perl,Ruby,Lua,Tcl,Scala,MaxScript 等脚本语言交流。
社区管理员
  • 脚本语言(Perl/Python)社区
  • WuKongSecurity@BOB
加入社区
  • 近7日
  • 近30日
  • 至今

试试用AI创作助手写篇文章吧