【问题标题】:Match sting in files and calculate total number of occurance匹配文件中的字符串并计算出现的总数
【发布时间】:2016-06-10 13:38:39
【问题描述】:

我有两个文件,一个是关键字文件,另一个是搜索文件

搜索.txt
play       dream
dream      play
dream

keyword.txt

play
dream

我想计算游戏和梦想的总出现次数,例如play= 2, dream =3

到目前为止我尝试过的代码是:

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

#Lexical variable for filehandle is preferred, and always error check opens.
open my $keywords,    '<', 'keyword.txt' or die "Can't open keywords: $!";
open my $search_file, '<', 'search.txt'   or die "Can't open search file: $!";
my $count=0;
my $keyword_or = join '|', map {chomp;qr/\Q$_\E/} <$keywords>;
my $regex = qr|\b($keyword_or)\b|;

while (<$search_file>)
{

    while (/$regex/g)
    {
    $count++;
        print "$.: $1\n";
        print($count);


    }
}

但它正在计算总出现次数,即 5

【问题讨论】:

  • 使用逗号和句号。请。
  • 没有,有两个文件,一个是关键字,例如dream和play,另一个是多行,包含dream和play。我们需要的是从第一个文件中获取关键字并找到总数。关键字在其他中的出现次数
  • 所以 play=2 和 dream=3 这应该是预期的输出

标签: perl file


【解决方案1】:

您可以使用哈希来计算单词出现的次数。关键字作为散列的键,计数作为值。

while (/$regex/g){
    $hash{$1}++;
}

# print the hash    
foreach(keys %hash){
    print "$_ : $hash{$_}\n";
}

【讨论】:

  • % 是用于在 Perl 中声明哈希的符号。哈希是 Perl 中的数据类型,有关更多信息,您应该查看 perldata
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-01-19
  • 2020-05-04
  • 2014-04-20
  • 2016-04-28
  • 1970-01-01
相关资源
最近更新 更多