2017-07-28 45 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