Python-将混合数转换为浮点数

Zac*_*ach 3 python mixed numbers

我想创建一个将混合数字和分数(作为字符串)转换为浮点数的函数.以下是一些例子:

'1 1/2' -> 1.5
'11/2' -> 5.5
'7/8' -> 0.875
'3' -> 3
'7.7' -> 7.7
Run Code Online (Sandbox Code Playgroud)

我目前正在使用这个功能,但我认为它可以改进.它也不处理已经是十进制表示的数字

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
Run Code Online (Sandbox Code Playgroud)

谢谢!

Ign*_*ams 8

2.6有fractions模块.只需将字符串拆分为空格,将块提供给fractions.Fraction(),调用float()结果,然后将它们全部添加.