advanced number recognition in strings?

Heiko Wundram me at modelnine.org
Mon May 8 19:01:37 EDT 2006


Am Montag 08 Mai 2006 19:03 schrieb s.schmeier at gmail.com:
> we want extract numbers from strings and wonder if there is already a
> module around for doing this. An example in our case would look like
> this:
>
> 0.032 +/- 0.5 x 10(-4)

Should work beautifully with the re.finditer function (untested!):

>>>
import re
numre = re.compile(r"""([+-]?[0-9]+(\.[0-9]*)?) # 0.032 matches this
                       (\s*+/-\s*([0-9]+(\.[0-9]*)))? # +/- 0.5 matches this
                       (\s*10\(([+-]?[0-9]+)\))? # 10(-4) matches this.""",
                   re.X)
data = """<your data here>"""
for match in numre.finditer(data):
    number = float(match.group(1))
    if match.group(4) is not None:
        prec = float(match.group(4))
    else:
        prec = 0
    if match.group(7) is not None:
        mantissa = int(match.group(7))
    else:
        mantissa = 0
    print number, prec, mantissa
>>>

--- Heiko.



More information about the Python-list mailing list