当前位置:  开发笔记 > 编程语言 > 正文

提取浮点/双精度值

如何解决《提取浮点/双精度值》经验,为你挑选了3个好方法。



1> jfs..:

来自的一个正则表达式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']


findall表达是业务,谢谢

2> S.Lott..:

这是简单的方法.不要将regex用于内置类型.

try:
    x = float( someString )
except ValueError, e:
    # someString was NOT floating-point, what now?



3> Dmitriy Yusu..:

对于parse int和float(点分隔符)值:

re.findall( r'\d+\.*\d*', 'some 12 12.3 0 any text 0.8' )

结果:

['12', '12.3', '0', '0.8']

推荐阅读
手机用户2402851335
这个屌丝很懒,什么也没留下!
DevBox开发工具箱 | 专业的在线开发工具网站    京公网安备 11010802040832号  |  京ICP备19059560号-6
Copyright © 1998 - 2020 DevBox.CN. All Rights Reserved devBox.cn 开发工具箱 版权所有