【问题标题】:Comparing two files for identical lines where the order doesn't matter比较两个文件的顺序无关紧要的相同行
【发布时间】:2011-05-09 02:13:39
【问题描述】:

我有两个文件(最长可达 150,000 行;每行 160 个字节),我想检查每个文件中的行是否相同。 diff 对我不起作用(直接),因为一小部分行在两个文件中以不同的顺序出现。通常,一对线将被转置。
查看两个文件中是否出现相同行但顺序无关紧要的最佳方法是什么? 谢谢, 克里斯

【问题讨论】:

    标签: file comparison


    【解决方案1】:

    另一个执行此操作的 python 脚本:

    #!/usr/bin/env python
    import sys
    
    file1 = sys.argv[1]
    file2 = sys.argv[2]
    
    lines1 = open(file1,'r').readlines()
    lines2 = open(file2,'r').readlines()
    lines1.sort()
    lines2.sort()
    
    s = ''
    for i,line in enumerate(lines1):
        if lines2[i] != line:
            print '> %s' % line
            print '< %s' % lines2[i]
            s = 'not'
    
    print 'file %s is %s like file %s' % (file1, s, file2)
    

    【讨论】:

      【解决方案2】:

      虽然这是一种稍微昂贵的方法(对于任何更大的事情,我都会重新考虑这个),但我会启动 python 并执行以下操作:

      filename1 = "WHATEBVER YOUR FILENAME IS"
      filename2 = "WHATEVER THE OTHER ONE IS"
      file1contents = set(open(filename1).readlines())
      file2contents = set(open(filename2).readlines())
      if file1contents == file2contents:
          print "Yup they're the same!"
      else:
          print "Nope, they differ.  In file2, not file1:\n\n"
          for diffLine in file2contents - file1contents:
              print "\t", diffLine
          print "\n\nIn file1, not file2:\n\n"
          for diffLine in file1contents - file2contents:
              print "\t", diffLine
      

      如果它们不同,它将打印不同的行。

      【讨论】:

      • 谢谢 - 我刚刚用 Python 写了一些类似的东西,因为现在还没有时髦的 Unix 巫术魔法可以做到这一点。问题解决了!
      • 对每个文件进行排序然后运行 ​​diff?
      • 是的 (+1),你 100% 正确,我只是讨厌使用临时文件!在 python 中的 15 秒内,我可以得到答案并可以访问 python 变量中的不同行...
      【解决方案3】:

      对于只有 150k 行,只需对每一行进行哈希处理并将它们按顺序存储在查找表中。然后对文件 2 中的每一行执行查找。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2018-05-19
        • 2014-03-21
        • 2023-03-15
        • 1970-01-01
        • 1970-01-01
        • 2012-05-29
        相关资源
        最近更新 更多