2014-11-03 89 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

相关问题