gpt4 book ai didi

python - 如何使用正则表达式将字符串中的 2.5k 数字格式化为 2.5e3

转载 作者:行者123 更新时间:2023-11-30 22:14:17 26 4
gpt4 key购买 nike

我正在使用 python 解析一个包含字符串数学表达式的 SPICE 文件,并将文本文件转换为 Python 脚本。

文件中数学表达式的示例是:

expr = 'k1 + 4.35k + 3.69meg*(pow(2.4u, 2*km2))'

我想找到表达式中的所有缩放因子并将它们转换为指数值:

scaling_factors = {
'g' : 'e9',
'meg': 'e6',
'k' : 'e3',
'm' : 'e-3',
'u' : 'e-6',
'n' : 'e-9',
}

我想要的输出是这样的:

converted_expr = 'k1 + 4.35e3 + 3.69e6*(pow(2.4e-6, 2*km2))'

我尝试过这个:

digits_re = r"([0-9]*\.[0-9]+|[0-9]+)k"
sample = 'k1 + 4.3k'
print(re.sub(digits_re, digits_re.replace('k', 'e3'), sample))

输出:

k1 + \\de3

但是不起作用

最佳答案

使用负前瞻 ( (?<=...) ) 确保符号之前有一个数字,并使用字边界断言 ( \b ) 来捕获“km2”情况:

import re
expr = re.sub(r"(?<=\d)k\b", "e3", expr)

如果您想避免多次执行此操作,可以使用函数作为替换值:

def sn_replace(match):
return scaling_factors[match.group(1)]

expr = re.sub(r"(?<=\d)(g|k|meg|m|u|n)\b", sn_replace, expr)

当第二个参数为 re.sub 时是一个函数,不是用文本替换匹配,而是使用匹配对象调用该函数,并使用其返回值作为替换。

关于python - 如何使用正则表达式将字符串中的 2.5k 数字格式化为 2.5e3,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50563691/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com