2014-11-03 44 views
0

所以我有我想要一個代碼:如果詞匹配,更換第n個字段只

如果UniqueID的從文件1 =的UniqueID從文件2:

更換第n個字段的UniqueID文件1

實施例的數據:

名稱:

啵武武洙Choo的

浦噓哞哞洙秋

辜噓盧武秀秋

噢噢噓浦武秀秋

OtherNames:

IIO噓哞哞洙秋

Too Boo ROO Moo Fuc Choo

噢噢噓YOO武秀秋

通緝最終結果:

噓新武秀秋

浦噓哞哞洙秋

辜噓盧武秀Choo

Ooo Boo NEW M Oo Soo Choo

infile = path 
filename = "Names.txt" 

otherin = path 
othfile = "OtherNames.txt" 

otherpth = os.path.join(otherin,othfile) 
path = os.path.join(infile,filename) 

mop = open(otherpth,"r") 
rdmo = mop.readlines() 
L = list(rdmo) 

doc = open(path,"r") 
doc2 = doc.readlines() 
k = list(doc2) 

for words in k: 
    wordsplit = words.split(" ") 
    first = wordsplit[0] 
    sec = wordsplit[1] 
    third = wordsplit[2] 
    fourth = wordsplit[3] 
    fifth = wordsplit[4] 
    sixth = wordsplit[5] 
    allwords = first +" "+ sec +" "+ third +" "+ fourth +" "+ fifth+" "+sixth 

    for entry in L: 
     entsplit = entry.split(" ") 
     a = entsplit[0] 
     b = entsplit[1] 
     c = entsplit[2] 
     d = entsplit[3] 
     e = entsplit[4] 
     f = entsplit[5].replace("\n","") 
     mtch = a +" "+ b+" "+ c+" "+ d+" "+ e+" "+f 

     if first == a: 
      newword = allwords[:8]+"NEW "+allwords[12:] 

      final = path 
      text = "NamesFinal.txt" 
      finaltext = os.path.join(final,text) 
      docfinal = open(finaltext,"w") 

      for lines in doc2: 
       G = lines.replace(allwords,newword) 
       docfinal.write(G) 

目前,它只是吐出了Ooo的最後一個循環。再次,我希望它可以吐出名稱文本文件,除了那些更改爲新的字段。

+0

你確定你不想「噢噢噓YOO武秀秋」,在輸出有一個「新」? – inspectorG4dget 2014-11-03 00:31:12

+0

不要不要它。我只是想讓第三個項目替換爲那些匹配的項目。對不起,如果這是令人困惑,因爲它有一個新的。 – 2014-11-03 00:36:51

回答

1

每一行匹配將在第三列

import csv 

with open('path/to/names') as infile: 
    db1 = {} 
    for row in csv.reader(infile, delimiter=' '): 
     db1[row[0]] = row 

with open('path/to/otherNames') as infile: 
    db2 = set() 
    for row in csv.reader(infile, delimiter=' '): 
     db2.add(row[0]) 

for k in db1: 
    if k in db2: 
     db1[k][2] = "NEW" 

with open('path/to/names') as infile, open('path/to/output', 'w') as outfile: 
    writer = csv.writer(outfile, delimiter=' ') 
    for line in csv.reader(infile, delimiter=' '): 
     k = line[0] 
     writer.writerow(db1[k]) 
+0

不,不,YOO,抱歉的混亂。我想要NEW。 – 2014-11-03 00:38:00

+0

@JoshClayton:完成!一切匹配現在將被替換爲「新」 – inspectorG4dget 2014-11-03 00:39:43

+0

太棒了!謝謝你的工作! – 2014-11-03 00:48:37