2011-01-23 64 views
1

我有两个单词列表(180k和260k),并且我想生成第三个文件,它是出现在两个列表中的单词集合。两个大单词列表的交集

这样做的最佳方法是什么?我读过论坛讨论使用grep,但我认为单词列表对于这种方法来说太大了。

回答

4

如果对这两个文件进行排序(或者可以对它们进行排序),则可以使用comm -1 -2 file1 file2打印出相交点。

+0

事实证明,它们中的一个分类 - 你能不能给我一个命令排序的另一个? – pjama 2011-01-23 06:04:47

+0

只要`sort -o outfile infile`,假设其他文件也按字母顺序排序。不过,要注意场所。特别是订单是“AaBb”还是“ABab”可以更改。为了安全起见,您可能需要明确地对两个文件进行排序,以确保您使用的是相同的设置。 – 2011-01-23 06:07:03

+0

谢谢你的帮助耶利米!排序工作正常,但*通讯*仍然警告'通信:文件2不是在排序顺序' - 但它似乎已经产生*东西*。这听起来不错吗?我会在早上做一些质量保证:) – pjama 2011-01-23 06:19:04

3

你是对的,grep将是一个坏主意。输入“man加入”并按照说明操作。

如果你的文件的话在一列刚刚名单,或者至少,如果重要的词是第一次在每一行,那么所有你需要做的是:

$ sort -b -o f1 file1 
$ sort -b -o f2 file2 
$ join f1 f2 

否则,可能需要给加盟(1)命令的一些附加说明:

JOIN(1)     BSD General Commands Manual     JOIN(1) 

NAME 
    join -- relational database operator 

SYNOPSIS 
    join [-a file_number | -v file_number] [-e string] [-o list] [-t char] [-1 field] [-2 field] file1 file2 

DESCRIPTION 
    The join utility performs an ``equality join'' on the specified files and writes the result to the standard output. The ``join field'' is the field in each file by which the files are compared. The 
    first field in each line is used by default. There is one line in the output for each pair of lines in file1 and file2 which have identical join fields. Each output line consists of the join field, 
    the remaining fields from file1 and then the remaining fields from file2. 
    . . . 
    . . . 
2

。假定每行一个字,我会用grep

grep -xFf seta setb 
  • -x整个线(没有部分匹配)
  • -F解释字面上给定的图案(没有正则表达式)
  • -f seta指定模式来搜索
  • setb是要搜索的内容的文件相匹配的seta

comm会做同样的事情,但需要你的设置要预先排序:

comm -12 <(sort seta) <(sort setb) 
1

grep -P '[ A-Za-z0-9]*' file1 | xargs -0 -I {} grep {} file2 > file3

我相信这会在文件1东西,然后检查是否在文件2什么是文件1,并把匹配到文件3什么。