python - Data sorting, combining 2 lines -
i have file looking way:
;1;108/1;4, 109 ;1;51;4, 5 ;2;109/2;4, 5 ;2;108/2;4, 109 ;3;108/2;4, 109 ;3;51;4, 5 ;4;109/2;4, 5 ;4;51;4, 5 ;5;109/2;4, 5 ;5;40/6;5, 6, 7
where
;id1;id2;position_on_shelf_id2 ;id1;id3;position_on_shelf_id3
as result, want get: id1;id2-id3;x x common shelf positions both id2 , id3, should this
1;108/1-51;4 2;109/2-108/2;4 3;108/2-51;4 4;109/2-51;4, 5 5;109/2-40/6;5
my script works fine moment need type common shelf positions. tried using .intersection, not working properly, when have positions consisting of double characters (pos:144-result: 14; pos:551, result: 51; pos:2222-result: 2 i.e)
result = id2_chars.intersection(id3_chars)
any fix intersection? or maybe better method on mind?
code far:
part1 - merge every 2nd line together
exp = open('output.txt', 'w') open("dane.txt") f: content = f.readlines() strng = "" in range(1,len(content)+1): strng += content[i-1].strip() if % 2 == 0: exp.writelines(strng + '\n') strng = "" exp.close()
part2 - intersection: exp = open('output2.txt', 'w')
imp = open('output.txt') line in imp: none, lp1, dz1, poz1, lp2, dz2, poz2 = line.split(';') s1 = poz1.lower() s2 = poz2.lower() s1_chars = set(s1) s2_chars = set(s2) result = s1_chars.intersection(s2_chars) result = str(result) exp.writelines(lp1 + ';' + dz1 + '-' + dz2 + ';' + result + '\n') exp.close()
** did not filtered result needs yet (it in "list" form), won't problem once right intersection result
your main problem try intersect 2 sets of characters while should intersect positions. should @ least use:
... s1 = poz1.lower() s2 = poz2.lower() s1_poz= set(x.strip() x in s1.split(',')) s2_poz = set(x.strip() x in s1.split(',')) result = s1_poz.intersection(s2_poz) result = ', '.join(result) ...
but in fact, whole processing in 1 single pass:
exp = open('output.txt', 'w') open("dane.txt") f: old = none line in f: # 1 line @ time enough line = line.strip() if old none: # first line of block, store old = line else: # second line of bock, process both none, lp1, dz1, poz1 = old.split(';') none, lp2, dz2, poz2 = line.split(';') poz1x = set(x.strip() x in poz1.tolower().split(',')) poz2x = set(x.strip() x in poz2.tolower().split(',')) result = ', '.join(poz1x.intersection(poz2x)) exp.write(lp1 + ';' + dz1 + '-' + dz2 + ';' + result + '\n') old = none
Comments
Post a Comment