Wednesday, 15 August 2012

python - Uneven character line split -



python - Uneven character line split -

i having problem building on code have used previously. have input file containing 6 pieces of info per row. problem there not whitespace utilize delimiter split each row , want split row in uneven steps of 4/4/4/8/8/4 characters i.e. so:

' 0 0 -16-50.6123 115.393 2'

would split (0,0,-16,-50.6123,115.393,2). utilize info form dictionary key array of first 3 numbers [0,0,-16] , homecoming value array of final 3 numbers [-50.6123,115.393,2].

the code used before when info separated whitespace (which can't alter since comes elsewhere) below. there nice way modify code have accommodate new uneven splitting of lines.

thanks!

def formatter(lines): line in lines: if not line.strip(): go on yield [to_float(item) item in line.split()] dct1 = {} open('test.txt') f1: row in formatter(f1): dct1[tuple(row[:3])] = row[3:6]

if know piece widths, i'd chop line slices. should give idea:

my_string =' 0 0 -16-50.6123 115.393 2' widths=[4,4,4,8,8,4] my_start=0 my_end=0 w in widths: my_end+=w print my_string[my_start:my_end] #or whatever want my_start+=w

output:

0 0 -16 -50.6123 115.393 2

python split delimiter

No comments:

Post a Comment