如何从字符串中提取浮点数

161 投票
7 回答
361994 浏览
提问于 2025-04-16 10:02

我有一些字符串,比如 Current Level: 13.4 db.,我想从中提取出浮点数。这里我说的是浮点数,而不是小数,因为有时候它是整数。请问正则表达式能做到这一点吗,还是有更好的方法?

7 个回答

37

Python文档中有一个答案,讲解了加号、减号和指数表示法。

scanf() Token      Regular Expression
%e, %E, %f, %g     [-+]?(\d+(\.\d*)?|\.\d+)([eE][-+]?\d+)?
%i                 [-+]?(0[xX][\dA-Fa-f]+|0[0-7]*|\d+)

这个正则表达式不支持国际格式,其中用逗号作为整数部分和小数部分之间的分隔符(比如3,14159)。在这种情况下,可以把上面浮点数的正则表达式中的所有\.替换为[.,]

                        Regular Expression
International float     [-+]?(\d+([.,]\d*)?|[.,]\d+)([eE][-+]?\d+)?
89

你可以试试下面这个方法,它考虑了所有的情况,包括不依赖数字后面的空格:

>>> import re
>>> numeric_const_pattern = r"""
...     [-+]? # optional sign
...     (?:
...         (?: \d* \. \d+ ) # .1 .12 .123 etc 9.1 etc 98.1 etc
...         |
...         (?: \d+ \.? ) # 1. 12. 123. etc 1 12 123 etc
...     )
...     # followed by optional exponent part if desired
...     (?: [Ee] [+-]? \d+ ) ?
...     """
>>> rx = re.compile(numeric_const_pattern, re.VERBOSE)
>>> rx.findall(".1 .12 9.1 98.1 1. 12. 1 12")
['.1', '.12', '9.1', '98.1', '1.', '12.', '1', '12']
>>> rx.findall("-1 +1 2e9 +2E+09 -2e-9")
['-1', '+1', '2e9', '+2E+09', '-2e-9']
>>> rx.findall("current level: -2.03e+99db")
['-2.03e+99']
>>>

方便复制粘贴:

numeric_const_pattern = '[-+]? (?: (?: \d* \. \d+ ) | (?: \d+ \.? ) )(?: [Ee] [+-]? \d+ ) ?'
rx = re.compile(numeric_const_pattern, re.VERBOSE)
rx.findall("Some example: Jr. it. was .23 between 2.3 and 42.31 seconds")
323

如果你的浮点数总是用小数形式表示,比如说

>>> import re
>>> re.findall("\d+\.\d+", "Current Level: 13.4db.")
['13.4']

这样就可以了。

一个更稳妥的版本是:

>>> re.findall(r"[-+]?(?:\d*\.*\d+)", "Current Level: -13.2db or 14.2 or 3")
['-13.2', '14.2', '3']

如果你想验证用户输入的内容,你也可以直接检查它是否是浮点数:

user_input = "Current Level: 1e100 db"
for token in user_input.split():
    try:
        # if this succeeds, you have your (first) float
        print(float(token), "is a float")
    except ValueError:
        print(token, "is something else")

# => Would print ...
#
# Current is something else
# Level: is something else
# 1e+100 is a float
# db is something else
        

撰写回答