文本文件之间的交集

4
我该如何计算两个文本文件之间的交集,以原始文本为基础?解决方案可以使用Shell命令或用Python、Elisp或其他常见脚本语言表达。
我知道“comm”和“grep -Fxv -f file1 file2”。这两种方法都假定我对的交集感兴趣,而我对字符的交集感兴趣(匹配所需的最少字符数)。
如果能提供高效的解决方案将获得额外加分。 示例 如果文件1包含以下内容:
foo bar baz-fee

文件2包含以下内容:

fee foo bar-faa

那么我想看到:

  • foo bar
  • 费用

假设最小匹配长度为3。


那么你是按单词进行比较吗?还是比较两个文件中出现的长度≥3的所有子字符串?(我不知道是否有通用的Unix工具;你可能需要进行一些动态规划。) - Josh Lee
3个回答

8
你正在寻找Python的difflib模块(在标准库中),特别是difflib.SequenceMatcher

2
这就是我喜欢这个网站的原因。我每天都能学到新东西。 - matchew

2

好的,这里有一个非常简单的Python脚本可以完成此任务。

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

temp.txt

xx yy xyz zz aa
xx yy xyz zz aa
xx yy xyz zz aa
xx yy 111 aa cc

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

0
你可以尝试调整diff的选项:http://ss64.com/bash/diff.html 不过我还不太明白你具体在问什么。根据你的定义,什么算一个单词?这里又是如何定义交集过程的呢?

任何字符序列都算作一个单词。同时出现在两个文件中的字符序列属于交集集合的一部分。例如,如果最小匹配长度为1,则两个文件中都使用的所有字母都是交集集合的一部分(如果存在更长的公共序列,则也包括在内)。 - ahmex

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接