Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/perl/10.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
在perl中比较散列中的键值对_Perl_Compare_Hash - Fatal编程技术网

在perl中比较散列中的键值对

在perl中比较散列中的键值对,perl,compare,hash,Perl,Compare,Hash,我有一个散列,键值是标量字符串。该值是另一个散列,该散列将字符串中的单词作为键,其频率作为值 结构: { doc1 => { w1 => freq1 , w2 => freq2, .....} , doc2 => { w1 => freq1 , w2 => freq2, .....} , . . . } 我想比较两个按键DOC1,doc2。。。并找出两个文档之间的常用词。对于所有文档对,所需输出是两个文档之间常用词的频率之和 哪种方法

我有一个散列,键值是标量字符串。该值是另一个散列,该散列将字符串中的单词作为键,其频率作为值

结构:

 { 
  doc1 => { w1 => freq1 , w2 => freq2, .....} ,
  doc2 => { w1 => freq1 , w2 => freq2, .....} ,
  .
  .
  .
}
我想比较两个按键DOC1,doc2。。。并找出两个文档之间的常用词。对于所有文档对,所需输出是两个文档之间常用词的频率之和

哪种方法最好?

类似于

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

# Sum of frequencies
my @frequencies;

# First doc
my $doc1 = {
    w1 => 1 , w2 => 5, w3 => 1
};

# Second doc
my $doc2 = {
    w1 => 3 , w2 => 2, w3 => 1, w4 => 12
};

# see first doc
foreach my $word (keys %{$doc1}) {
    if (exists $doc2->{$word}) {
        push (@frequencies, {$word => $doc1->{$word} + $doc2->{$word}});
    }
    else {
        push (@frequencies, {$word => $doc1->{$word}});
    }

    delete $doc2->{$word};
}

# see second doc
foreach my $word (keys %{$doc2}) {
    push (@frequencies, {$word => $doc2->{$word}});
}

# See sum of frequencies
print join "\n", map {sprintf("%s: %s", keys %$_, values %$_)} @frequencies;

1;
输出

$ perl compare.pl
w3: 2
w1: 4
w2: 7
w4: 12

你试过什么?你遇到了什么问题?请显示您的Perl代码,以及输入和所需输出的示例。请阅读