这里我的代码可以为我获取x和y的系数,但我没有得到截距项!
eq = ["1x+1y+2", "-1x+12Y-6", "2-5y-3x", "7y-50+2X", "3.14x-1.5y+9", "11.0x-1.5y+9.8"]
def coefficients(equation):
import re
coef_x = re.findall('-?[0-9.]*[Xx]', equation)[0][:-1]
coef_y = re.findall('-?[0-9.]*[Yy]', equation)[0][:-1]
intercept = re.findall("b[+-]?d+[.]?[d]+b|[+-]?d+[+-]|[+-]?d+[s]", equation)
#return float(coef_x), float(coef_y), intercept
print(coef_x, coef_y, intercept)
print("")
for i in eq:
coefficients(i)
输出:
1 1 []
-1 12 []
-3 -5 ['2-']
2 7 ['-50+']
3.14 -1.5 []
11.0 -1.5 []
预期:
1 1 2
-1 12 -6
-3 -5 2
2 7 -50
3.14 -1.5 9
11.0 -1.5 9.8
如果有人能提出必要的改变,我会非常感激,这样我就可以得到正确的拦截
试试这个:
import re
eq = ["1x+1y+2", "-1x+12Y-6", "2-5y-3x", "7y-50+2X", "3.14x-1.5y+9", "11.0x-1.5y+9.8"]
x = re.compile("([+-]?d+(.d+)?)[xX]")
y = re.compile("([+-]?d+(.d+)?)[yY]")
z = re.compile("([+-]?d+(.d+)?)([+-]|$)")
for line in eq:
xx = 0
m = x.search(line)
if m:
xx = m.group(1)
yy = 0
m = y.search(line)
if m:
yy = m.group(1)
zz = 0
m = z.search(line)
if m:
zz = m.group(1)
print("X = "+ xx + ", Y = " + yy + ", intercept= " + zz)
实际上,您可以使用前瞻断言使用一个正则表达式来查找系数,这不会推进正则表达式引擎的扫描位置。
(?i)(?=.*?(-?[d.]+(?=x)))(?=.*?(-?[d.]+(?=y)))(?=.*?(-?[d.]+(?=(?:+|-|$))))
参见Regex Demo
例如,要查找拦截:
(?= # start of a positive lookahead assertion
.*? # match 0 or more characters non-greedily
( # start of capture group 3
-? # match optional "-"
[d.]+ # match number (not very sophisticated)
(?= # start of a new positive lookahead assertion that must be met
(?: # start of a non-capture group
+ # match "+"
| # or
- # match "-"
| # or
$ # end of string
)
)
)
)
本质上,我们正在寻找一个后面跟着"+"、"-"或字符串末尾的数字。同样,为了找到x的系数,我们寻找一个后面跟着"x"的数字:
(?= # start of a positive lookahead assertion
.*? # match 0 or more characters non-greedily
( # start of capture group 1
-? # match optional "-"
[d.]+ # match number (not very sophisticated)
(?= # start of a new positive lookahead assertion that must be met
x # match "x"
)
)
)
代码:
import re
eq = ["1x+1y+2", "-1x+12Y-6", "2-5y-3x", "7y-50+2X", "3.14x-1.5y+9", "11.0x-1.5y+9.8"]
regex = re.compile(r'(?i)(?=.*?(-?[d.]+(?=x)))(?=.*?(-?[d.]+(?=y)))(?=.*?(-?[d.]+(?=(?:+|-|$))))')
for ex in eq:
m = regex.search(ex)
if m:
print(m.group(1), m.group(2), m.group(3))
打印:
1 1 2
-1 12 -6
-3 -5 2
2 7 -50
3.14 -1.5 9
11.0 -1.5 9.8
同一问题的新解决方案。
eq = ["1x+1y+2", "-1x+12Y-6", "2-5y-3x", "7y-50+2X", "3.14x-1.5y+9", "11.0x-1.5y+9.8"]
def coefficients(equation):
import re
coef_x = re.findall('-?[0-9.]*[Xx]', equation)[0][:-1]
coef_y = re.findall('-?[0-9.]*[Yy]', equation)[0][:-1]
intercept = re.sub("[+-]?d+[XxYy]|[+-]?d+.d+[XxYy]","", equation)
return float(coef_x), float(coef_y), float(intercept)
for i in eq:
print(coefficients(i))
输出:
(1.0, 1.0, 2.0)
(-1.0, 12.0, -6.0)
(-3.0, -5.0, 2.0)
(2.0, 7.0, -50.0)
(3.14, -1.5, 9.0)
(11.0, -1.5, 9.8)