gpt4 book ai didi

python - 提取浮点/ double 值

转载 作者:IT老高 更新时间:2023-10-28 22:13:01 26 4
gpt4 key购买 nike

如何使用正则表达式从字符串中提取 double 值。

import re

pattr = re.compile(???)
x = pattr.match("4.5")

最佳答案

来自perldoc perlretut 的正则表达式:

import re
re_float = re.compile("""(?x)
^
[+-]?\ * # first, match an optional sign *and space*
( # then match integers or f.p. mantissas:
\d+ # start out with a ...
(
\.\d* # mantissa of the form a.b or a.
)? # ? takes care of integers of the form a
|\.\d+ # mantissa of the form .b
)
([eE][+-]?\d+)? # finally, optionally match an exponent
$""")
m = re_float.match("4.5")
print m.group(0)
# -> 4.5

从更大的字符串中提取数字:

s = """4.5 abc -4.5 abc - 4.5 abc + .1e10 abc . abc 1.01e-2 abc 
1.01e-.2 abc 123 abc .123"""
print re.findall(r"[+-]? *(?:\d+(?:\.\d*)?|\.\d+)(?:[eE][+-]?\d+)?", s)
# -> ['4.5', '-4.5', '- 4.5', '+ .1e10', ' 1.01e-2',
# ' 1.01', '-.2', ' 123', ' .123']

关于python - 提取浮点/ double 值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/385558/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com