多个文件之间的交集

0 投票
2 回答
984 浏览
提问于 2025-04-18 01:42

我有多个文件(比如说3个)。每个文件只有一列,内容大概是这样的:

文件 A

America
Russia
China
UK

文件 B

India
China
Russia

文件 C

China
America
Russia
Iran

现在,为了找出这些文件中共同的元素,我会这样做:

python -c 'import sys;print "".join(sorted(set.intersection(*[set(open(a).readlines()) for a in sys.argv[1:]])))' File1 File2 File3 File4

但是,如果我还想知道这些文件之间的成对重叠情况,我该怎么做呢?也就是说,我想得到一个包含所有文件共同元素的集合,以及只在文件 A 和 B、A 和 C、C 和 B 中出现的元素。

如果能提供一些 Python 的帮助,那就太好了。

请帮帮我。

2 个回答

1

你可以简单地用 set 来实现这个功能:

>>> print list(set(open(f1)) & set(open(f2)) & set(open(f3)))

如果是针对特定的文件,你可以这样做:

>>> print list(set(open(f1)) & set(open(f2)))
>>> print list(set(open(f1)) & set(open(f3)))
>>> print list(set(open(f2)) & set(open(f3)))

根据 @HerrActress 的建议,这样做可以处理字符串中的 \n 部分:

[i.strip() for i in (set(open(f1)) & set(open(f2)))]

2

要找出所有文件中都出现的行,你可以使用:

for f in sys.argv[1:]:
    data = []
    with open(f) as inp:
           lines = set(line.rstrip() for line in  inp)
           data.append(lines)
    common_lines = data[0].intersection(*data[1:])

对于第二部分,可以使用 itertools.combinations

from itertools import combinations

for f1, f2 in combinations(sys.argv[1:], 2):
    with open(f1) as inp1, open(f2) as inp2:
        print set(line.rstrip() for line in inp1).intersection(map(str.rstrip,
                                                                           inp2))

撰写回答