【问题标题】:Intersection between text files文本文件之间的交集
【发布时间】:2011-09-22 20:12:48
【问题描述】:

如何根据原始文本计算两个文本文件之间的交集?解决方案是使用 shell 命令还是用 Python、Elisp 或其他常见脚本语言表达都没有关系。

我知道commgrep -Fxv -f file1 file2。两者都假设我对 lines 的交集感兴趣,而我对 characters 的交集感兴趣(最少需要算作匹配的字符数)。

效率加分。

示例

如果文件 1 包含

foo bar baz-fee

并且文件 2 包含

fee foo bar-faa

那我想看看

  • foo bar
  • fee

假设最小匹配长度为 3。

【问题讨论】:

  • 所以你说的是文字?或者两个文件中出现的每个长度≥3的子字符串? (我不知道通用的 unix 工具;您可能需要进行一些动态编程。)

标签: python bash text emacs grep


【解决方案1】:

您正在寻找 Python 的 difflib 模块(在标准库中),尤其是 difflib.SequenceMatcher

【讨论】:

  • 这就是我喜欢这个网站的原因。我每天都能学到新东西。
【解决方案2】:

好的,这里有一个非常简单的 python 脚本来完成这个

它可以改进,但应该能胜任。

temp.txt

xx yy xyz zz aa
xx yy xyz zz aa
xx yy xyz zz aa
xx yy 111 aa 抄送

temp2.​​txt

yy aa cc dd
ff xx ee 11
oo mm aa tt

common.py

#!/usr/bin/python
import sys

def main():
    f1,f2 = tryOpen(sys.argv[1],sys.argv[2])
    commonWords(f1,f2)
    f1.close()
    f2.close()

def tryOpen(fn1,fn2):
    try:
      f1 = open(fn1, 'r')
      f2 = open(fn2, 'r')
      return f1,f2
    except Exception as e:
      print('Oh No! => %s' %e)
      sys.exit(2) #Unix programs generally use 2 for 
                  #command line syntax errors
                  # and 1 for all other kind of errors.

def commonWords(f1,f2):

    words = []
    for line in f1:
      for word in line.strip().split():
            words.append(word)
    for line in f2:
        for word in line.strip().split():
            if word in words: print 'common word found => %s' % word    
if __name__ == '__main__':
    main()

输出

./common.py temp.txt temp2.txt
common word found => yy
common word found => aa
common word found => cc
common word found => xx
common word found => aa

【讨论】:

    【解决方案3】:

    您可以尝试使用 diff 选项:http://ss64.com/bash/diff.html

    不过,我仍然不清楚您的具体要求。你定义中的一个词是什么?以及这里的交叉过程是如何定义的?

    【讨论】:

    • 任何字符序列都算作一个单词。两个文件中出现的字符序列是交集的一部分。例如,最小匹配长度为 1,两个文件中使用的所有字母都是交集的一部分(以及更长的公共序列,如果它们存在的话)。
    猜你喜欢
    • 2015-04-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-09-09
    相关资源
    最近更新 更多