在两个文件中打印公共行

时间:2014-04-01 18:31:24

标签: python python-2.7 python-3.x

我有两个文件:

file1 = "He is a man\n He likes the football\n The tennis is a popular game\n His work is very interessing \n He comes from Rome\n"

file2 = "is a man/[VF]\n popular game/[Af]\n the football/[DN]"

我想做什么:如果file1中存在file2中的一行(没有注释),那么我想在file1中替换此行,但是使用注释(例如/ [Af])。

所以我的结果应该是这样的:

file1 = "He is a man[VF]\n He likes the football[DN]\n The tennis is a popular game[Af]\n His work is very interessing \n He comes from Rome\n"

我试过这样的事情:

delimiter = '/'

    for line in file2.splitlines():
        if delimiter in line:
            newline = line.strip()
            tag = line[line.index(delimiter):-1].strip()
            tok = line[1:line.index(delimiter)].strip()
            for l in file1.splitlines():
                print l.replace(tok, newline)        

但问题是结果重复过多

1 个答案:

答案 0 :(得分:0)

由于很难理解你想要做什么,所以只有一般的过程:如果你的第二个文件不是太大而不适合内存,只需创建一个字典d,其中键是源行,值是你想要替换的行。之后

result = [d.get(line,line) for line in file1]

会做到这一点。它不是最快的方式,但足够合理使用。在python中的字典用聪明的数学搜索它的键,所以它很快。