嗨伙计们!
我想请你帮忙。我已经开始学习PYTHON,有一项任务我想不通如何完成。所以就是这样了。
我们有一个input.txt文件,其中包含以下4行:
- f(x, 3*y) * 54 = 64 / (7 * x) + f(2*x, y-6)
-
- x + f(21*y, x - 32/y) + 4 = f(21 ,y)
-
- 86 - f(7 + x*10, y+ 232) = f(12*x-4, 2*y-61)*32 + f(2, x)
-
- 65 - 3* y = f(2*y/33 , x + 5)
任务是将"f"函数和它的两个参数改为除法。这两个参数之间可以有不同的空格量。例如,f(2,5)与f(2,5)相同,在代码运行后,f(2,5)应该是(2/5),并且在分隔符前后恰好有一个空格。此外,如果其中一个参数是乘法或除法,则该参数必须放在方括号中。例如:F(3,5*7)应变为(3/(5*7))。并且一行中可以有任意数量的函数。因此,输出应如下所示:
- (x / (3*y)) * 54 = 64 / (7 * x) + ((2*x) / (y-6))
-
- x + ((21*y) / (x - 32/y)) + 4 = (21 / y)
-
- 86 - ((7 + x*10) / (y+ 232)) = ((12*x-4) / (2*y-61))*32 + (2 / x)
-
- 65 - 3* y = ((2*y/33) / (x + 5))
如果有人能帮我,我会很高兴的。
先谢谢你,
大卫
# 回答1
以下是使用Re解决方案的简化版本,其中显示了替换字符串的无条件格式。我会让您来最终确定格式。
- import re
-
- s = "86 - f(7 + x*10, y+ 232) = f(12*x-4, 2*y-61)*32 + f(2, x) - 12*6"
- patt = re.compile(r'(f\((.[^)]+)\))')
-
- start = 0
- end = len(s)
- while True:
- m = patt.search(s, start, end)
- if m:
- s1 = m.group(1)
- s2 = m.group(2)
- a,b = [ss.strip() for ss in s2.split(",")]
- s = s.replace(s1, "(%s) / (%s)" % (a,b), 1)
- start = m.end()+1
- else:
- break
结果字符串:
- >>> s
- '86 - (7 + x*10) / (y+ 232) = (12*x-4) / (2*y-61)*32 + (2) / (x) - 12*6'
# 回答2
非常感谢,你帮了我很大的忙。现在我或多或少都明白了。这有点难以破译:
- patt = re.compile(r'(f\((.[^)]+)\))')
。
但是,我尝试给它一些条件,比如如果f()调用的左侧或右侧包含"+、-、*、/"标记,则用带括号的标记替换它。它只适用于前两个调用函数,但忽略了第三个函数。我不知道为什么,我试着打印每一个有用的信息,看起来搜索就是找不到第三个,无论从哪里开始。你能在这件事上也帮我吗?我很抱歉给你带来这个问题,但我真的很想了解它是如何工作的。提前谢谢您。代码如下:
- import re
-
- s = "86 - f(7 + x*10, y+ 232) = f(12*x-4, 2*y-61)*32 + f(2, x) - 12*6"
- patt = re.compile(r'(f\((.[^)]+)\))')
-
- start = 0
- end = len(s)
- while True:
- m = patt.search(s, start, end)
- if m:
- s1 = m.group(1)
- s2 = m.group(2)
- a,b = [ss.strip() for ss in s2.split(",")]
- if "+" in b or "-" in b or "*" in b or "/" in b:
- b = b.replace(b, "(%s)" % b)
- else:
- print "Nothing.";
-
- if "+" in a or "-" in a or "*" in a or "/" in a:
- a = a.replace(a, "(%s)" % a)
- else:
- print "Nothing.";
-
- s = s.replace(s1, "(%s / %s)" % (a,b), 1)
- start = m.end()+1
- else:
- break
-
- print s
# 回答3
实际上,我不需要使用开始和结束变量。这是导致错过第三场比赛的原因。Search方法将查找匹配字符串的第一个匹配项。使用前一个匹配项重新定义字符串后,将找到下一个匹配项。我对其他一些东西进行了修改,这样它就可以工作了。
- import re
-
- s = "86 - f(7 + x*10, y+ 232) = f(12*x-4, 2*y-61)*32 + f(2, x) - 12*6"
- patt = re.compile(r"(f\((.[^)]+)\))")
-
- while True:
- m = patt.search(s)
- if m:
- s1 = m.group(1)
- s2 = m.group(2)
- a,b = [ss.strip() for ss in s2.split(",")]
- if "+" in b or "-" in b or "*" in b or "/" in b:
- b = "(%s)" % b
- if "+" in a or "-" in a or "*" in a or "/" in a:
- a = "(%s)" % a
- s = s.replace(s1, "(%s / %s)" % (a,b), 1)
- else:
- break
- print s
希望内联代码能够正确显示:
Patt=re.Compile(r'(f\((.[^)]+)\)')
# 回答4
以下是解释Re模式的尝试
R'(f\(([^)]+)\))'