多个文件之间的交叉点

时间:2014-04-07 12:24:52

标签: python file

我有多个文件(比如说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 个答案:

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

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