如果单词匹配,则仅替换第n个字段

时间:2014-11-03 00:23:43

标签: python python-2.7 if-statement for-loop text

所以我有一个我想要的代码:

如果file1中的UniqueID = file2中的UniqueID:

替换UniqueID file1的第n个字段

示例数据:

姓名:

Boo Moo Moo Soo Choo

Poo Boo Moo Moo Soo Choo

Koo Boo Loo Moo Soo Choo

Ooo Boo Poo Moo Soo Choo

OtherNames:

IIo Boo Moo Moo Soo Choo

Boo ROO Moo Fuc Choo

Ooo Boo YOO Moo Soo Choo

通缉最终结果:

Boo NEW Moo Soo Choo

Poo Boo Moo Moo Soo Choo

Koo Boo Loo Moo Soo Choo

Ooo Boo NEW Moo 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的最后一个循环。再一次,我希望它吐出Names文本文件,除非这些字段更改为New。

1 个答案:

答案 0 :(得分: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])