[英]python replace multiple occurrences of string with different values
i am writing a script in python that replaces all the occurrences of an math functions such as log with there answers but soon after i came into this problem i am unable replace multiple occurrences of a function with its answer我正在 python 中编写一个脚本,它将所有出现的数学函数(例如日志)替换为那里的答案,但在我遇到这个问题后不久,我无法用它的答案替换多次出现的 function
text = "69+log(2)+log(3)-log(57)/420"
log_list = []
log_answer = []
z = ""
c = 0
hit_l = False
for r in text:
if hit_l:
c += 1
if c >= 4 and r != ")":
z += r
elif r == ")":
hit_l = False
if r == "l":
hit_l = True
log_list.append(z)
if z != '':
logs = log_list[-1]
logs = re.sub("og\\(", ";", logs)
log_list = logs.split(";")
for ans in log_list:
log_answer.append(math.log(int(ans)))
for a in log_answer:
text = re.sub(f"log\\({a}\\)", str(a), text)
i want to replace log(10) and log(2) with 1 and 0.301 respectively i tried using re.sub but it is not working i am not able to replace the respective functions with there answers any help will be appreciated thank you我想分别用 1 和 0.301 替换 log(10) 和 log(2) 我尝试使用 re.sub 但它不起作用我无法用那里的答案替换相应的功能任何帮助将不胜感激谢谢
As long as your string contains no spaces and there are +
signs between different logarithmic functions, eval
could be a way to do it.只要您的字符串不包含空格并且不同的对数函数之间有+
号, eval
可能是一种方法。
>>> a = 'log(10)+log(2)'
>>> b = a.split('+')
>>> b
['log(10)', 'log(2)']
>>> from math import log10 as log
>>> [eval(i) for i in b]
[1.0, 0.3010299956639812]
EDIT: You could repeatedly use str.replace
method to replace all mathematical operators (if there are more than one) with whitespaces and eventually use str.split
like:编辑:您可以重复使用str.replace
方法用空格替换所有数学运算符(如果有多个),并最终使用str.split
,如:
>>> text.replace('+', ' ').replace('-', ' ').replace('*', ' ').replace('/', ' ').split()
['69', 'log(2)', 'log(3)', 'log(57)', '420']
Here is my take on this using eval
along with re.sub
with a callback function:这是我使用eval
和re.sub
以及回调 function 对此的看法:
x = "log(10)+log(2)"
output = re.sub(r'log\((\d+(?:\.\d+)?)\)', lambda x: str(eval('math.log(' + x.group(1) + ', 10)')), x)
print(output) # 1.0+0.301029995664
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.