Suppose I have a sympy expression like this:
假设我有这样一个表达式:
x = ( 1+ r70f * C2H4 *H+ r71* O)
where r70f, C2H4, H , r71, O
are sympy variables. I want it to change it to the following expression:
其中r70f,C2H4,H,r71,O是同源变量。我希望它将其更改为以下表达式:
x = ( 1+ k(r70f) * c(sC2H4) *c(sH)+ k(r71)* c(sO))
Basically replace r_SomeNumber_f
to k(r_SomeNumber_f)
and replace C2H4
or H
or O
to c(sC2H4)
or c(sH)
or c(sO)
respectively.
基本上将r_SomeNumber_f替换为k(r_SomeNumber_f)并分别将C2H4或H或O替换为c(sC2H4)或c(sH)或c(s0)。
I am trying to use regular expressions but re.sub
need str
, but they are all sympy
objects and that is making things complicated!!!
我试图使用正则表达式,但re.sub需要str,但它们都是sympy对象,这使事情变得复杂!
1 个解决方案
#1
1
I'm demonstrating two ways to do this: one with symbol trickery and the other with a wrapper function:
我正在演示两种方法:一种是带符号技巧,另一种是带有包装函数:
>>> ns={}
>>> ns["O"] = Symbol("O")
>>> x = S('1+ r70f * C2H4 *H+ r71* O', locals=ns)
>>> # Symbol trickery -- changing the name to have parens in it
>>> print(x.replace(
... lambda x: re.match('r[0-9]+f', str(x)),
... lambda x: Symbol('k(%s)' % str(x))))
...
C2H4*H*k(r70f) + O*r71 + 1
# function wrapper
>>> k=Function('k')
>>> print(x.replace(lambda x: re.match('r[0-9]+f', str(x)), lambda x:k(x)))
C2H4*H*k(r70f) + O*r71 + 1
NOTE: You said that you were looking for k_number_f but the case of r71 does not end with an 'f' so it isn't changed.
注意:您说您正在寻找k_number_f,但r71的情况并非以'f'结尾,因此不会更改。
I leave as an extension the conversion of the others which get wrapped with the 'c-function'.
我将其他包含'c-function'的转换作为扩展留下。
#1
1
I'm demonstrating two ways to do this: one with symbol trickery and the other with a wrapper function:
我正在演示两种方法:一种是带符号技巧,另一种是带有包装函数:
>>> ns={}
>>> ns["O"] = Symbol("O")
>>> x = S('1+ r70f * C2H4 *H+ r71* O', locals=ns)
>>> # Symbol trickery -- changing the name to have parens in it
>>> print(x.replace(
... lambda x: re.match('r[0-9]+f', str(x)),
... lambda x: Symbol('k(%s)' % str(x))))
...
C2H4*H*k(r70f) + O*r71 + 1
# function wrapper
>>> k=Function('k')
>>> print(x.replace(lambda x: re.match('r[0-9]+f', str(x)), lambda x:k(x)))
C2H4*H*k(r70f) + O*r71 + 1
NOTE: You said that you were looking for k_number_f but the case of r71 does not end with an 'f' so it isn't changed.
注意:您说您正在寻找k_number_f,但r71的情况并非以'f'结尾,因此不会更改。
I leave as an extension the conversion of the others which get wrapped with the 'c-function'.
我将其他包含'c-function'的转换作为扩展留下。