打印哈希键和值(如果匹配)

时间:2015-02-23 16:49:22

标签: perl hash matching fuzzy-search

我正在尝试将哈希与文件匹配。但是,由于标点符号和空格,我正在搜索的内容与文件不完全匹配。例如,我可能在我的哈希中有“JE Industries,Incorporated”,在我的文件中有“JE Industries Incorporated”。由于“,”逗号,这两者显然不匹配。

所以我的解决方案是使用哈希和文件并对每个文件执行修改(替换文件和哈希值中的标点符号,以便'JE Industries,Incorporated'将匹配'JE Industries Incorporated',以及其他一组规则。)一旦满足匹配,请转到该文件的哈希中的下一项。如果不满足匹配,请转到下一个规则“elsif”,并尝试匹配,如果满足,请转到下一个项目等。我还希望有一个未修改的哈希和行副本,以便每个原件都没有修改。所以基本上一次只应用一条规则。

所以我一直在努力解决这个问题,但我的结果并不是我想要的。

CODE

 open(my $fh, "list.txt");

    while(<$fh>) {
     my($line) = $_;
     chomp($line);
    my %hash = (
        12345 => 'JE Industries, Incorporated',
        123355 => 'Josh Industries, Inc'
    );
    while( my( $key, $value ) = each %hash ) {
    if($value =~ s/[[:punct:]]//gi eq $line =~ s/[[:punct:]]//gi) {print $line,",",$key,"\n";} #replace punctuation on both $line and $value to make them match##
    elsif($value =~ s/[\s]//gi eq $line =~ s/[\s]//gi) {print $value,",",$key,"\n";} ## if punctuation does not do it replace space##

}
}

我的档案,list.txt

JE Industries Incorporated
Josh Industries Inc
Jim bob&amp;合。

我的输出

JE Industries Incorporated,123355
Josh Industries Inc,123355

所需的输出

JE Industries Incorporated,“JE Industries,Incorporated”,12345
Josh Industries Inc,“Josh Industries,Inc”,123355

original_Value_from_file,“original_Value_from_hash”,每个对应的键

它匹配我的项目从哈希到文件,但是,它只是从哈希中为每个值分配最后一个键。另外,我有点不确定如何打印每行/哈希的原始形式以及匹配结果。还要记住,对于修改,我想从一开始就为每个规则修改它们。换句话说,在第二个规则发生的地方,“$ value = ~s / [\ s] // gi eq $ line = ~s / [\ s] // gi”,我想替换“JE Industries”中的\ s ,“不在”JE Industries Incorporated。“

最后,我希望我的结果是哈希值,$ line值的原始形式以及它们对应的哈希键的匹配的原始形式。我还想要实现更多的规则,而不仅仅是省略标点符号和空格来进行更接近的匹配。

1 个答案:

答案 0 :(得分:1)

很多时候,提前准备数据更容易。 为了使你的代码以后更简单。

以下是我要为id创建非标点符号名称的反向哈希。

循环文件时,我必须将我的非标点符号与id hash进行比较才能找到匹配项。

下面的工作示例

use strict;
use warnings;
my %id_to_name = (
    12345  => 'JE Industries, Incorporated',
    123355 => 'Josh Industries, Inc'
);
#Create a reverse map with out any punctuation
my %no_punc_name_to_id;
while (my ($key, $value) = each %id_to_name) {
    $value =~ s/[[:punct:]]//gi;
    $no_punc_name_to_id{$value} = $key;
}
my $filename = 'list.txt';
open my $fh , '<' , $filename or die "Cannot read '$filename': $!";

while(my $line = <$fh>)  {
    chomp($line);
    $line =~ s/[[:punct:]]//gi;
    if(exists $no_punc_name_to_id{$line}) {
        my $id = $no_punc_name_to_id{$line};
        print $line,",","\"$id_to_name{$id}\"",",",$id,"\n";
    }
}
相关问题