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 :)