打印两个文件中的公用行

2024-03-28 22:32:59 发布

您现在位置:Python中文网/ 问答频道 /正文

我有两个文件:

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]"

我想做的是:如果file2中有一行(没有注释)出现在file1中,那么我想用注释替换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)        

但问题是结果过于重复


Tags: theingameislinefile1file2he
1条回答
网友
1楼 · 发布于 2024-03-28 22:32:59

因为很难理解您想做什么,这里只讲一般的过程:如果您的第二个文件不是太大而无法放入内存,那么只需创建一个字典d,其中键是源行,值是要替换的行。之后呢

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

会成功的。这不是最快的方法,但使用起来足够合理。python中的字典使用聪明的数学搜索其键,因此速度很快。你知道吗

相关问题 更多 >