【问题标题】:Compare two text files in Perl在 Perl 中比较两个文本文件
【发布时间】:2015-07-08 03:26:02
【问题描述】:

我在两个 .txt 文件中有几个字符串。它们都包含一些相似的字符串,但没有排列在同一个行号上。

例如, 文件1.txt 卡门 爱迪生 莫莉 杰森 达蒙 杰拉德

file2.txt 爱迪生 杰森

我想将在两个文本文件(在本例中为 Edison Jason)中找到的相似字符串保存到一个数组中。

【问题讨论】:

  • 我们在这里帮助您完成任务,而不是为您完成。请告诉我们你有什么并提出更具体的问题。

标签: arrays string perl file text


【解决方案1】:

有各种数组实用程序库可以实现这一点 - 你的目标是交集,Array::Utils 是实现这一点的更简单的库之一;

#!/usr/bin/env perl
use strict;
use warnings;

use File::Slurp qw(read_file);
use Array::Utils qw(intersect);

my $file1 = 'file1.txt';
my $file2 = 'file2.txt';

my @data1 = split( /\s/, read_file($file1) );
my @data2 = split( /\s/, read_file($file2) );

my @intersect = intersect( @data1, @data2 );

print join(', ', @intersect), "\n";

或者,不需要 Array::Utils

#!/usr/bin/env perl
use strict;
use warnings;

my @data1 = qw( Carmen Edison Molly Jason Damon Gerard );
my @data2 = qw( Edison Jason );

sub intersect {
  my %e = map { $_ => undef } @{$_[0]};
  return grep { exists( $e{$_} ) } @{$_[1]};
}

my @intersect = intersect( \@data1, \@data2 );
print join(', ', @intersect), "\n";

【讨论】:

  • 它对我不起作用,因为我的 linux 无法找到 Array/Utils.pm。我正在使用我公司的电脑来处理这个问题。
  • 你需要从命令行 `sudo cpan Array::Utils' 安装 Array::Utils,或者直接从 github.com/salmonix/Analictica_perl/blob/master/AUtils/… 复制 intersect sub
  • 命令说我不允许执行 '/usr/bin/cpan Array::Utils' 有没有别的办法写代码?
  • 是的,将我之前评论中的链接中的 sub 复制到您的代码中,并删除示例中对 Array::Utils 的引用
  • 效果不佳。我试过 Text::Diff 但从来没有像我想要的那样工作。
【解决方案2】:

无需使用额外的模块

#!/usr/bin/env perl
use strict;
use warnings;

my @data1 = qw( Carmen Edison Molly Jason Damon Gerard );
my @data2 = qw( Edison Jason );
my @data3 = ();

foreach my $d1 ( @data1 )
{
    chomp $d1;

    foreach my $d2 ( @data2 )
    {
        chomp $d2;

        if( $d1 eq $d2 )
        {
            print "Match Found : $d1, $d2 \n";
            push @data3, $d1;
        }
    }
}

【讨论】:

    【解决方案3】:

    你可以这样做,而无需安装任何额外的模块

    #!/usr/bin/perl
    use warnings;
    use strict;
    
    my (@file1,@file2,@match);
    
    open FILE1, "<", 'file1.txt';
    @file1 = <FILE1>;
    close FILE1;
    
    open FILE2, "<", 'file2.txt';
    @file2 = <FILE2>;
    close FILE2;
    
    chomp (@file1,@file2);
    
    foreach(@file1) {
        if ($_ ~~ @file2) {
            push @match, $_;
        }
    }
    
    print "\nMatches\n";
    foreach(@match) { print "The same -- $_\n"; }
    

    【讨论】:

      猜你喜欢
      • 2014-02-16
      • 2014-06-14
      • 2011-08-25
      • 2018-09-05
      • 1970-01-01
      • 1970-01-01
      • 2018-08-17
      • 2012-03-18
      • 2014-05-31
      相关资源
      最近更新 更多