python - 使用Python的正则表达式在某些字符之间插入符号

标签 python regex replace insert

我正在制作一个数学程序,允许用户输入方程式,程序将解决它。我正在努力使其尽可能用户友好。我希望用户能够轻松地输入方程式,而不必担心在每个乘法实例之间添加乘法符号。

这是一个示例:

用户输入:y=xy+yz 程序输出:y=x*y+y*z

我已经能够使用 Python 的 re 模块轻松完成此任务,如下所示:

equation = "y=xy+yz"
equation = re.sub(r"([xyzuvet])([xyzuvet])",r"\1*\2", equation)  # x,y,z,u,v,e, and t and variables and constants the user can use in their equation.
equation = re.sub(r"([xyzuvet])([xyzuvet])",r"\1*\2", equation)  # Must run twice in the event the equation looks something like y=xyzxyz

但是,当我引入诸如 y=yexp(x) 之类的特殊函数时,我遇到了问题。当我运行上面的代码时,我将得到 y=y*e*xp(x) 的输出。

我后来更新了我的代码以考虑 pi:

equation = re.sub(r"([xyzuve]|pi)([xyzuve]|pi)",r"\1*\2", equation)
equation = re.sub(r"([xyzuve]|pi)([xyzuve]|pi)",r"\1*\2", equation)

我想我可以使用上面类似的方法来匹配 exp 并防止它在 'e' 和 'x' 之间添加 * ,如下所示:

equation = re.sub(r"([xyzuve]|pi|exp)([xyzuve]|pi|exp)",r"\1*\2", equation)
equation = re.sub(r"([xyzuve]|pi|exp)([xyzuve]|pi|exp)",r"\1*\2", equation)

我认为通过像pi一样添加exp,它会起作用;但不幸的是它不起作用。有没有办法将 exp 和其他也包含 x、y、z、u、v、t 和 e 的函数视为一个整体?

以下是我希望输入的一些示例:

输入:y=eexp(xyz) 输出:y=e*exp(x*y*z)

输入:y=pifrexp(yt) 输出:y=pi*frexp(y*t)

输入:y=sin(x)exp(y) 输出:y=sin(x)*exp(y)

最佳答案

这似乎产生了你想要的:

equation = re.sub(r"([)xyzuvet]|pi|exp|frexp)([xyzuvet]|pi|exp|frexp)\b",r"\1*\2", equation)
equation = re.sub(r"([)xyzuvet]|pi|exp|frexp)([xyzuvet]|pi|exp|frexp)\b",r"\1*\2", equation)

例如:

>>> import re
>>> eqns = ('y=eexp(xyz)', 'y=pifrexp(yt)', 'y=sin(x)exp(y)')
>>> for equation in eqns:
...     equation = re.sub(r"([)xyzuvet]|pi|exp|frexp)([xyzuvet]|pi|exp|frexp)\b",r"\1*\2", equation)
...     equation = re.sub(r"([)xyzuvet]|pi|exp|frexp)([xyzuvet]|pi|exp|frexp)\b",r"\1*\2", equation)
...     print equation
... 
y=e*exp(x*y*z)
y=pi*frexp(y*t)
y=sin(x)*exp(y)

关于python - 使用Python的正则表达式在某些字符之间插入符号,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32776205/

相关文章:

python - 了解 tf.extract_image_patches 以从图像中提取补丁

javascript - 如何用 `replace`方法将多个关键字替换成相应的关键字?

regex - 如何找到所有 .git\config 文件?

python - 使用 Python 脚本仅返回特定值

c# - 在字符串之后替换 - 在字符之前

python - 如果字符串段落中的项目属于字符串列表,则删除它们?

python - Tensorboard 图像摘要

python - 使用全局单例实例将子进程对象存储在内存中

java - 使用 System.loadLibrary 加载 Python C 扩展 DLL

java - 使用正则表达式提取子字符串