求解:关于执行字符串中包含的方法的一点疑惑

0 views
Skip to first unread message

Yul Chino

unread,
Feb 8, 2010, 3:29:21 AM2/8/10
to python-cn`CPyUG`华蟒用户组(中文Py用户组)
其实问题是“百度知道”上的,具体如下:
----------------------------
初始字符串:
"f(x)= x + 2-3\nbox = f(2) + 2\nbox = f(f(2)) + 2\nfunc = 3 + 3 * 4\n"
目标字符串:
"box = 1 + 2\nbox = 0 + 2\nfunc = 3 + 3 * 4\n"
-----------------------------
由于本人还处于《可爱的Python》中所描述的小白阶段,反正看到这题觉的还蛮有意思的。
看到一位老大的回答:
‘’‘’‘’‘’‘’‘’‘’‘’‘’‘’‘’‘’‘’‘’‘’‘’‘’‘’‘’‘’‘’
import re

src = 'f(x)= x + 2 - 3\nbox = f(2) + 2\nbox = f(f(2)) + 2\nfunc = 3 +
3 * 4\n'
des = []
p = re.compile(r'f\(\d+\)')
pro = src.split('\n')

def f(x):
return eval(pro[0].split('=')[1])

def call_f(match):
x = int(re.search(r'\d+', match.group()).group())
return str(f(x))

for line in pro:
if line.startswith('f(x)'):
continue
else:
while p.search(line):
line = p.sub(call_f, line)
des.append(line)

print '\n'.join(des)
‘’‘’‘’‘’‘’‘’‘’‘’‘’‘’‘’‘’‘’‘’‘’‘’‘’‘’‘’‘’‘’
不过觉得有些不够“精炼”,于是也依葫芦画瓢的写了一个:
‘’‘’‘’‘’‘’‘’‘’‘’‘’‘’‘’‘’‘’‘’‘’‘’‘’‘’‘’‘’‘
import re
src = 'f(x)= x + 2 - 3\nbox = f(2) + 2\nbox = f(f(2)) + 2\nfunc = 3 +
3 * 4\n'

p = re.compile(r'f\([^()]\)')
n = src.find('\n')

func = src[:n]
content = src[n+1:]
exec func.replace('f(x)=','f=lambda x:')

def call_f(match):
exec 'res='+match.group()
return str(res)

while p.search(content):
content = p.sub(call_f,content)

print content
’‘’‘’‘’‘’‘’‘’‘’‘’‘’‘’‘’‘’‘’‘’‘’‘’‘’‘’‘’‘’
看起来似乎好一些了,但总有些不对味的感觉,还远远达不到“精巧”,想请诸位老大给些
提示,看法啥的
-------
最后,还有一个小疑问,由于我的代码是脱胎于第一种,其实里面有一个还没有想明白的东西,
这里的call_f方法中match参数是从哪里产生的啊?不知其所以然啊,难道在sub的时候,自动生成了
这么个玩意?看了re.py,只有个match方法啊,求教Ing...

victor lee

unread,
Feb 8, 2010, 7:15:17 AM2/8/10
to pyth...@googlegroups.com
sub(pattern, repl, string, count=0, flags=0)

repl can be either a string or a callable;
If it is a callable, it's passed the match object and must return a replacement string to be used.
2010/2/8 Yul Chino <yuan...@gmail.com>

--
来自: `python-cn`:CPyUG ~ 华蟒用户组 | 发言:pyth...@googlegroups.com
退订: http://tinyurl.com/45a9tb //针对163/qq邮箱:http://tinyurl.com/4dg6hc
详情: https://groups.google.com/group/python-cn
严正: 理解列表! 智慧提问! http://wiki.woodpecker.org.cn/moin/AskForHelp

大熊

unread,
Feb 8, 2010, 9:45:56 PM2/8/10
to pyth...@googlegroups.com
百度知道上有着这个,看来我得百度一下了

--
不是所有的特仑苏都是牛奶
Reply all
Reply to author
Forward
0 new messages