Extracting float numbers from file using python
Question: I have .txt file which looks like:

    
    
    [ -5.44339373e+00  -2.77404404e-01   1.26122094e-01   9.83589873e-01
       1.95201179e-01  -4.49866890e-01  -2.06423297e-01   1.04780491e+00]
     [  4.34562117e-01  -1.04469577e-01   2.83633101e-01   1.00452355e-01   -7.12572469e-01  -4.99234705e-01  -1.93152897e-01   1.80787567e-02] 
    

I need to extract all floats from it and put them to list/array

What I've done is this:

    
    
    A = []
    for line in open("general.txt", "r").read().split(" "):
        for unit in line.split("]", 3):
            A.append(list(map(lambda x: str(x), unit.replace("[", "").replace("]", "").split(" "))))
    

but `A` contains elements like `['']` or even worse `['3.20973096e-02\n']`.
These are all strings, but I need floats. How to do that?


Answer: Why not use a regular expression?

    
    
    >>> import re
    >>> e = r'(\d+\.\d+e?(?:\+|-)\d{2}?)'
    >>> results = re.findall(e, your_string)
    ['5.44339373e+00',
     '2.77404404e-01',
     '1.26122094e-01',
     '9.83589873e-01',
     '1.95201179e-01',
     '4.49866890e-01',
     '2.06423297e-01',
     '1.04780491e+00',
     '4.34562117e-01',
     '1.04469577e-01',
     '2.83633101e-01',
     '1.00452355e-01',
     '7.12572469e-01',
     '4.99234705e-01',
     '1.93152897e-01',
     '1.80787567e-02']
    

Now, these are the matched _strings_ , but you can easily convert them to
floats:

    
    
    >>> map(float, re.findall(e, your_string))
    [5.44339373,
     0.277404404,
     0.126122094,
     0.983589873,
     0.195201179,
     0.44986689,
     0.206423297,
     1.04780491,
     0.434562117,
     0.104469577,
     0.283633101,
     0.100452355,
     0.712572469,
     0.499234705,
     0.193152897,
     0.0180787567]
    

Note, the regular expression might need some tweaking, but its a good start.

