使用正则表达式从线性函数中提取系数
Extract coefficient from a linear function using regex
我有这个功能
x1 +3 x2 +2 x3 -2.2 x4 +19 x5
我需要使用正则表达式
提取系数 [1, 3, 2, -2.2, 19]
我做了[^x][1-9],但不一般。例如,如果我有
3 x2 -2.2 x41 +19 x50
它将得到 [3, -2.2, 41, 19, 50] 而不是 [3, -2.2, 19]
然后我需要一些东西来处理这个问题,比如 [^x[1-9][1-9]] 但是如果我有 x124 或 x12345 或者
x 后 n 位。
我怎样才能排除它们并只得到系数?
import re
# define the problem
mystring='x1 +3 x2 +2 x3 -2.2 x4 +19 x5'
# get coefficients
regex_coeff='([+-]\d*\.{0,1}\d+) x'
# assuming your polynome is normalized, we can add the one in front
coeffs=[1.0] + [float(x) for x in re.findall(regex_coeff,mystring)]
# get exponents
regex_expo='x(\d+)'
exponents=[int(x) for x in re.findall(regex_expo,mystring)]
# print results
print(coeffs)
print(exponents)
>>[1.0, 3.0, 2.0, -2.2, 19.0]
>>[1, 2, 3, 4, 5]
我有这个功能
x1 +3 x2 +2 x3 -2.2 x4 +19 x5
我需要使用正则表达式
提取系数 [1, 3, 2, -2.2, 19]我做了[^x][1-9],但不一般。例如,如果我有
3 x2 -2.2 x41 +19 x50
它将得到 [3, -2.2, 41, 19, 50] 而不是 [3, -2.2, 19]
然后我需要一些东西来处理这个问题,比如 [^x[1-9][1-9]] 但是如果我有 x124 或 x12345 或者 x 后 n 位。
我怎样才能排除它们并只得到系数?
import re
# define the problem
mystring='x1 +3 x2 +2 x3 -2.2 x4 +19 x5'
# get coefficients
regex_coeff='([+-]\d*\.{0,1}\d+) x'
# assuming your polynome is normalized, we can add the one in front
coeffs=[1.0] + [float(x) for x in re.findall(regex_coeff,mystring)]
# get exponents
regex_expo='x(\d+)'
exponents=[int(x) for x in re.findall(regex_expo,mystring)]
# print results
print(coeffs)
print(exponents)
>>[1.0, 3.0, 2.0, -2.2, 19.0]
>>[1, 2, 3, 4, 5]