我想制作一个将混合数字和分数(作为字符串)转换为浮点数的函数。这里有一些例子:
'1 1/2' -> 1.5
'11/2' -> 5.5
'7/8' -> 0.875
'3' -> 3
'7.7' -> 7.7
我目前正在使用此功能,但我认为它可以改进。它也不处理已经是十进制表示的数字
def mixedtofloat(txt):
mixednum = re.compile("(\\d+) (\\d+)\\/(\\d+)",re.IGNORECASE|re.DOTALL)
fraction = re.compile("(\\d+)\\/(\\d+)",re.IGNORECASE|re.DOTALL)
integer = re.compile("(\\d+)",re.IGNORECASE|re.DOTALL)
m = mixednum.search(txt)
n = fraction.search(txt)
o = integer.search(txt)
if m:
return float(m.group(1))+(float(m.group(2))/float(m.group(3)))
elif n:
return float(n.group(1))/float(n.group(2))
elif o:
return float(o.group(1))
else:
return txt
谢谢!