3

我想制作一个将混合数字和分数(作为字符串)转换为浮点数的函数。这里有一些例子:

'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

谢谢!

4

3 回答 3

8

2.6 有fractions模块。只需在空格上拆分字符串,将块提供给fractions.Fraction(),针对结果调用float(),然后将它们全部加起来。

于 2010-05-21T00:06:12.547 回答
2

Ignacio 的回答可能是处理它的最佳方式,但如果您不使用 Python 2.6,您可以构建一个功能更简单,而不必依赖正则表达式。这是我放在一起的一个简单但不是很健壮的版本:

def parse_fraction(fraction):

    def parse_part(part):
        sections = part.split('/')
        if len(sections) == 1:
            return float(sections[0])
        return float(sections[0]) / float(sections[1])

    return sum( parse_part(part) for part in fraction.split() )

这显然不是完美的,因为它仍然会接受类似 的输入'2 1/2 1/2',它会评估为3,因为它本质上总结了一个以空格分隔的数字列表,同时根据需要将每个数字评估为分数。

如果您坚持使用基于正则表达式的解决方案,您应该知道您可以使用原始字符串来避免所有内容都使用双反斜杠。本质上,您可以编写:

mixednum = re.compile(r"(\d+) (\d+)/(\d+)")

字符串前面的r告诉 Python 不要评估字符串中的特殊字符,因此您可以编写文字反斜杠,它们将被视为这样。另请注意,您不需要转义斜杠,因为它不是 Python 正则表达式中的特殊字符(因为它不像许多语言那样用于标记文字正则表达式的边界)。该re.IGNORECASE标志在这里也没有多大意义,因为它只包含正则表达式中的数字实体,而且re.DOTALL也没有意义,因为你没有点可以应用它。

于 2010-05-21T02:53:23.010 回答
1

I wrote the Mixed class to extend fractions to do just that. Source is here.

>>> float(Mixed('6 7/8'))
6.875
>>> float(Mixed(1,1,2)) # 1 1/2
1.5
>>> float(Mixed('11/2')) # 11/2
5.5
于 2013-11-13T18:52:39.650 回答