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

'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

谢谢!

有帮助吗?

解决方案

2.6有 fractions 模块。只需将字符串拆分在空格上,将块馈送到 fractions.Fraction(), , 称呼 float() 相对于结果,并将它们全部添加。

其他提示

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正则表达式中的特殊字符(因为它不像许多语言一样用来标记字面的Regexp的边界)。这 re.IGNORECASE 标志在这里也没有很多意义,因为它仅在Regexp中包含数字实体,并且 re.DOTALL 也毫无意义,因为您没有可应用的点。

我写了 Mixed 课程扩展分数以做到这一点。来源是 这里.

>>> 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
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top