2017-07-28 27 views
-1

我有一个文件看是这样的:数据排序,结合2线

;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 

其中

;id1;id2;position_on_shelf_id2 
    ;id1;id3;position_on_shelf_id3 

结果,我想: ID1,ID2,ID3; X 其中x是id2和id3的常见货架位置,它应该看起来像这样

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 

我的脚本工作在我需要输入普通货架位置的那一刻起,这一点很好。我尝试使用.intersection,但它不能正常工作,当我有由双字符组成的位置(pos:144-result:14; pos:551,result:51; pos:2222-result:2 ie)

result = id2_chars.intersection(id3_chars) 

交叉点的任何修复?或者你的想法可能有一些更好的方法?

代码到目前为止:

part1的 - 合并每一第二线一起

exp = open('output.txt', 'w') 
with open("dane.txt") as f: 
    content = f.readlines() 
    strng = "" 
    for i in range(1,len(content)+1): 
     strng += content[i-1].strip() 
     if i % 2 == 0: 
      exp.writelines(strng + '\n') 
      strng = "" 

exp.close() 

第2部分 - 路口: EXP =开放( 'output2.txt', 'W')

imp = open('output.txt') 
for 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() 

**我没有过滤我的需求的结果(它是在“列表”形式),但它不会是一个问题,一旦我得到正确的交集结果

+0

请包含您到目前为止的代码。 – perigon

+0

添加代码(部分字母) – krizz

回答

1

您的主要问题是您尝试相交两组角色,而您应该相交位置。所以,你应该至少使用:

... 
s1 = poz1.lower() 
s2 = poz2.lower() 
s1_poz= set(x.strip() for x in s1.split(',')) 
s2_poz = set(x.strip() for x in s1.split(',')) 
result = s1_poz.intersection(s2_poz) 
result = ', '.join(result) 
... 

但事实上,你可以很容易地做一个单程全处理:

exp = open('output.txt', 'w') 
with open("dane.txt") as f: 
    old = None 
    for line in f:    # one line at a time is enough 
     line = line.strip() 
     if old is None:   # first line of a block, just store it 
      old = line 
     else:     # second line of a bock, process both 
      none, lp1, dz1, poz1 = old.split(';') 
      none, lp2, dz2, poz2 = line.split(';') 
      poz1x = set(x.strip() for x in poz1.tolower().split(',')) 
      poz2x = set(x.strip() for x in poz2.tolower().split(',')) 
      result = ', '.join(poz1x.intersection(poz2x)) 
      exp.write(lp1 + ';' + dz1 + '-' + dz2 + ';' + result + '\n') 
      old = None 
+0

谢谢,我昨天晚些时候在我自己的设备上找到了类似的解决方案 – krizz