0

I am struggling with converting a string with numbers (of which some are negative) into list of floats.

I am reading data from a file that has many numbers in each line. I want to make a list of floats from this numbers, to be able to work with them later. I am struggling with getting the negative numbers to be read correctly. In order to make things more clear I am running a function on each line of the input file, and I wish to get back floats in a list.

I tried isdigit(), float() and numerous regular expressions. So far with no success. The provided code shows some of the approaches I tried.

def find_float(input):
    temp_list = []
    print("line just now being read is: {} ".format(input))
    #1[DIDN'T WORK] number = re.findall(r"-?\d*\.\d+|\d+", input)
    #2[DIDN'T WORK] number = re.findall("([+-](?=\.?\d))?(\d+)?(\.\d+)", input)
    #3[DIDN'T WORK] number = re.findall(r"[-]?([1-9]{1}[0-9]{0,}(\.[0-9]{0,2})?|0(\.[0-9]{0,2})?|\.[0-9]{1,2})", input)
    #4[DIDN'T WORK] number = re.findall(r"\-?(\d+\.?\d*|\d*\.?\d+)", input)

    #5[DIDN'T WORK]for item in input:
    #                   try: 
    #                  number = float(item) 
    #                  extracted_numbers.append(number)

    print("Found number is: {}".format(number))
    temp_list.append(number) 
    return temp_list

All the regexpr above ommit the negative sign : they read neagitve numbers as positive. Other approaches left me without any negative numbers at all.

Input_file.txt: (please note that there are trailing white spaces at the end of each line)

0         8.42           43     -1.5
-259  0.832       
  522                   -32       
                     -3.33       
      12 -3 -45

I want be able to get lists like this for each line

[0, 8.42, 43, -1.5]

[-259, 0.832]

[522, -32]

[-3.33]

[12, -3, -45]

--Thanks in advance for any advice :)

2
  • 1
    Does your input file only contain whitespace separated numbers? If so, you could simply iterate over the lines and use the split method. Commented Oct 22, 2019 at 17:08
  • currently it does, but I want to keep it more general. Script will be used to import data from Matlab, and there might be various separators used. Commented Oct 24, 2019 at 8:23

2 Answers 2

2

With your sample data:

with open('Input_file.txt') as f:
  for line in f:
    data = [float(n) for n in line.split()]
    print(data)

Output:

[0.0, 8.42, 43.0, -1.5]
[-259.0, 0.832]
[522.0, -32.0]
[-3.33]
[12.0, -3.0, -45.0]
Sign up to request clarification or add additional context in comments.

Comments

0

Try this:

In [1]: with open('test.txt', 'r') as f: 
   ...:     data = f.readlines()

In [2]: results = []

In [3]: for line in data: 
    ...:     entry = [] 
    ...:     for num in line.split(' '): 
    ...:         if num.replace('-', '').strip().isdigit(): 
    ...:             entry.append(int(num)) 
    ...:         else: 
    ...:             try: 
    ...:                 entry.append(float(num)) 
    ...:             except Exception: 
    ...:                 pass 
    ...:     results.append(entry) 

In [4]: results                                                                                                                                                                         
Out[4]: 
[[0, 8.42, 43, -1.5],
 [-259, 0.832],
 [522, -32],
 [-3.33],
 [12, -3, -45]]

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.