Python parsing out parts of a string -
i have string can this:
scenario 1: "some_field=(parameter_a-0-(8.869834109e-05))/(0.001*10)"
or
scenario 2: "some_field=(parameter_a-(0.0005883943))/(0.001*10)"
how can parse out numbers in decimal format below?
scenario 1: first number: -0.00008869834109 second number: 0.01
scenario 2: first number: 0.0005883943 second number: 0.01
the string format stays same number format , polarities can change.
i think main work extract pieces contain numbers surrounding characters. can done .split()
, .find()
, .rfind()
, indexing within character strings.
my code assumes there 1 equal sign '=', number parts separated '/' , each enclosed in round brackets (in innermost if there more on bracket level), , there might sign directly left of inner-most bracket.
content = "some_field=(parameter_a-0-(8.869834109e-05))/(0.001*10)" content = "some_field=(parameter_a-(0.0005883943))/(0.001*10)" #or way ever give character strings content = content.split('=') #split @ equal sign if(len(content) != 2) : #check 1 equal sign print ('something wrong in data?') #in case information left of equal sign needed fieldname = content[0] content = content[1] #now work on part right of '=' content = content.split('/') values = [] in range(len(content)): x = content[i] pos_open = x.rfind( '(' ) #find position of opening bracket '(', starting right--> finds right-most pos_close = x.find( ')' ) #hence, digits in x[pos_open+1:pos_close] check uncommenting following line #print( x[pos_open+1:pos_close] ) #check whether there multiplication included in part if ( x[pos_open+1:pos_close].find('*') < 0 ) : # .find() returns -1 if character sequence not found val = float( x[pos_open+1:pos_close] ) # float() main work of conversion else: pos_dot = x[pos_open+1:pos_close].find('*') factor1 = float( x[pos_open+1: pos_open+1 + pos_dot] ) factor2 = float( x[pos_open+1 + pos_dot+1 : pos_close] ) val = factor1 * factor2 #check negative sign: (sorry, examples not show how sign specified) if (pos_open > 0 , x[pos_open - 1] == '-'): # checks character before bracket #note: in case of pos_open=0, second part x[pos_open - 1] @ last character x[-1] val = -val values.append(val) #output print ('first: {0} second: {1}' .format(values[0], values[1]) ) #standard way print ('first: ' + repr(values[0]) + ' second: ' + repr(values[1]) ) #another standard way print ('first: {0:.12f} second: {1:.7f}' .format(values[0], values[1]) ) # format specified in 2 exemplary ways
the extraction part of code work if there more 2 numbers stored in character string, grabs 1 group of characters @ time , appends determined value val
list values
.
Comments
Post a Comment