如果匹配则打印散列键和值

print hash keys and values if they are matched

我正在尝试将散列与文件相匹配。但是,由于标点符号和 spaces,我正在搜索的内容和文件并不完全匹配。例如,我的散列中可能有 "JE Industries, Incorporated",文件中有 "JE Industries Incorporated"。由于“,”,逗号,这两个显然不匹配。

所以我的解决方案是有一个散列和一个文件,并对每个文件进行修改(替换文件和散列值中的标点符号,这样 'JE Industries, Incorporated' 将匹配 'JE Industries Incorporated',以及其他集合规则。)一旦匹配得到满足,就转到文件哈希中的下一个项目。如果不满足该匹配项,请转到下一条规则 "elsif",并尝试匹配该规则,如果满足,请转到下一项等。我还想要一个未修改的散列和行副本,所以每一个的原件都没有被修改。所以基本上一次只应用一个规则。

所以我一直在研究如何解决这个问题,但我的结果不是我想要的。

代码

 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 工业公司
乔什工业公司
吉姆·鲍勃公司

我的输出

JE Industries Incorporated,123355
乔希工业公司,123355

期望输出

JE Industries Incorporated,"JE Industries, Incorporated",12345
乔希工业公司,"Josh Industries, Inc",123355

original_Value_from_file,"original_Value_from_hash",每个

对应的key

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

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

很多时候提前准备数据会更容易。 以后让你的代码更简单。

这是我要为 ID 创建非标点符号名称的反向哈希。

循环文件时,我只需将非标点符号与 id 哈希进行比较即可找到匹配项。

下面的工作示例

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";
    }
}