Python 删除两个文件中不常见的字符串

Python 删除两个文件中不常见的字符串,python,biopython,Python,Biopython,我有两个文件,文件1包含2列,文件2包含5列。 我想删除文件2中不包含文件1公共字符串的行: -文件1,如果这是一个列表,则每行包含[0]和[1] gene-3 + gene-2 - gene-1 - -文件2,将文件1中的[0]和[1]与此文件的[0]和[4]进行比较。如果文件1中的noline与文件2的任何行匹配,则必须删除 gene-1 mga CDF 1 + # this line contains + instead - although gane-1 is the s

我有两个文件,文件1包含2列,文件2包含5列。 我想删除文件2中不包含文件1公共字符串的行:

-文件1,如果这是一个列表,则每行包含[0]和[1]

gene-3  +
gene-2  -
gene-1  -
-文件2,将文件1中的[0]和[1]与此文件的[0]和[4]进行比较。如果文件1中的noline与文件2的任何行匹配,则必须删除

gene-1  mga CDF 1   +  # this line contains + instead - although gane-1 is the same. rm
gene-2  mga CDS 1   -  # [0][1] from file 1 = [0][4] from file 2: (gene-2, - ) keep it!
gene-3  mga CDH 1   +  # ""                 ""              ""
gene-4  mga CDS 1   +  # no gene-4 in file 1, remove.
-期望输出:

gene-3  mga CDH 1   +
gene-2  mga CDS 1   -

有什么想法吗?

在一个文件中创建一组不同的字符串,只在文件2中保留相交的线。这是一个有趣的问题,但不清楚您遇到的问题是哪一部分。你知道如何读/写文件吗?如何在空白处分割行?实际上,您的示例毫无意义,您将如何匹配文件2中的第四行?文件中有一个
+
和一个
-
1@PadraicCunningham我认为OP只是检查
gene-4
是否不在
file1
中,所以也将其从
file2
中删除。另一种情况是OP只想在
file2
file1
中保留那些在末尾具有相同符号
+
-
的条目。我需要将文件1中的[0]和[1]与文件2中的[0]和[4]进行比较。如果它们与任何列表都不匹配,请删除。您好,Steven,它会返回给我一个空文件。@Peaceandlove,别担心,我编辑的目的是将更新的内容覆盖到文件2,如果您想将其写入新文件,只需使用旧代码,边写边写。哦,没问题,我正在测试:),非常感谢!
with open('file1', 'r') as f:
    keepers = set(tuple(line.split()) for line in f)
with open('file2', 'r') as f_in, open('file3', 'w') as f_out:
    for line in f_in:
        parts = line.split()
        if (parts[0], parts[-1]) in keepers:
            f_out.write(line)
with open("file1.txt") as f, open("file2.txt") as f1:
    items  = set(line.rstrip() for line in f)
    filtered = [line for line in f1 if "  ".join(line.split()[::4]) in items]
    with open("file2.txt","w") as f3:
        f3.writelines(filtered)