查找文件集中的对

时间:2014-11-18 20:32:04

标签: python file dictionary

从数据文件集中,如何查找其他文件中是否有相同的对。

例如:我在col[0] col[1]中有5个带有节点对的文件,它们都是明确的对。

我必须检查所有5个文件中的所有对都重复。

任何建议都表示赞赏。

输入:只有一部分col[0]col[1]是要从所有5个文件中集中的列。

00022d7317d7 00022d9064bc 1073260810 1073276155 819251 440006 819251 440006
00022d9064bc 0030650497a0 1073260810 1073272525 819251 440006 819251 440006
00022d9064bc 00904b8150f1 1073260810 1073260999 819251 440006 819251 440006
00022d9064bc 00904ba69d11 1073260810 1073260857 819251 440006 819251 440006
0030650c9eda 0030658a61de 1073260811 1073260813 820356 439224 820356 439224
0030650c9eda 00904b16c23a 1073260811 1073260813 820356 439224 820356 439224
0030650c9eda 00904bacceaf 1073260811 1073260813 820356 439224 820356 439224
0030650c9eda 00904bf058d0 1073260811 1073260813 820356 439224 820356 439224
00022d0e0cec 0030650c9eda 1073260813 1073262843 820187 439271 820187 439271
00022d176cf3 00904ba8b682 1073260813 1073260962 817721 439564 817721 439564

预期输出

假设我们考虑第一行col[0]col[1]

00022d7317d7 00022d9064bc

我必须在所有5个文件中比较这一对,找出哪个文件以及该对出现的次数。我需要比较所有5个文件中的所有对。

注意:我知道这不是提供服务的代码。所以我很感激指导我到附近的样品或任何建议。谢谢!

1 个答案:

答案 0 :(得分:0)

根据最近的另一篇文章调整我的答案:

假设文件夹结构类似于/path/data1.txt /path/data2.txt ... /path/dataN.txt /path/script.py,其中没有其他文件。

  1. 初始化两个字典,用于跟踪所有文件的内容。一个将存储计数" 看到 N 次"另一个将存储文件中的文件名" pair [data1,data3] "
  2. 获取外部循环中的所有.txt个文件。对于每个文件:
    1. 读读内循环中的所有行。对于每一行:
      1. 拆分前两列,使用空格作为分隔符,调用一对
      2. 在一个字典中增加整体看到的次数
      3. 将当前文件名添加到该对的文件名列表中,在另一个词典中
  3. 然后在所有文件中都看到了位置列表长5的每一对。打印那些对。 然后转储计数字典以查看每对出现的次数。

    (未测试的):

    from glob import glob
    import os
    
    masterCount = {}
    masterLocations = {}
    
    for datafile in glob('*.txt'):
        filename = os.path.split(datafile)[1]
    
        for line in open(datafile):
            columns = line.split(' ')
            pair = columns[0] + ' ' columns[1]
    
            masterCount[pair] = masterCount.get(pair, 0) + 1
            masterLocations[pair] = masterLocations.get(pair, []) + [filename]
    
    for pair, filenames in masterLocations.iteritems():
        if len(filenames) == 5:
            print pair, "found in all 5 files"
    
    for pair, count in masterCount.iteritems():
        print: pair, "found", count, "times in total"