Python-将带分数转换为浮点数

发布于 2024-09-03 02:39:03 字数 772 浏览 4 评论 0原文

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

'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

谢谢!

I want to make a function that converts mixed numbers and fractions (as strings) to floats. Here's some examples:

'1 1/2' -> 1.5
'11/2' -> 5.5
'7/8' -> 0.875
'3' -> 3
'7.7' -> 7.7

I'm currently using this function, but I think it could be improved. It also doesn't handle numbers that are already in decimal representation

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

Thanks!

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

烟花肆意 2024-09-10 02:39:03

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

2.6 has the fractions module. Just split the string on whitespace, feed the chunks to fractions.Fraction(), call float() against the result, and add them all up.

梦里°也失望 2024-09-10 02:39:03

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' 这样的输入,它将评估为 < code>3,因为它本质上是对一个以空格分隔的数字列表进行求和,同时根据需要将每个数字计算为分数。

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

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

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

Ignacio's answer is probably the best way to handle it, but if you aren't using Python 2.6, you can build a function that does things a little more simply without having to rely on regular expressions. Here is a simple and not very robust version I threw together:

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() )

This obviously isn't perfect, because it will still accept input like '2 1/2 1/2', which it would evaluate as 3, since it essentially sums up a space delimited list of numbers while evaluating each as a fraction as necessary.

if you do stick with the regular expression based solution, you should know that you can use a raw string to avoid having to double backslash everything. Essentially, you can write:

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

The r in front of the string tells Python to not evaluate special characters within the string, so you can write literal backslashes and they will be treated as such. Also note that you do not need to escape the slash since it is not a special character in Python regular expressions (because it is not used to mark the borders of the literal regexp like in many languages). the re.IGNORECASE flag also doesn't make a lot of sense here, since it only includes numeric entities in the regexp, and re.DOTALL is also meaningless, since you have no dots for it to apply to.

╭ゆ眷念 2024-09-10 02:39:03

我编写了 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

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
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文