2015-02-23 93 views
1

我想匹配一个哈希文件。但是,由于标点符号和空格,我所搜索的文件和文件并不完全匹配。例如,我可能在我的文件中有“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实业股份有限公司
乔希工业公司
吉姆·鲍勃&合作。

我的输出

JE工业股份有限公司,123355
约什工业公司,123355

希望的输出

JE工业股份有限公司, “JE工业公司”,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 ,Incorporated“不在”JE Industries Incorporated。“。

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

回答

1

很多时间提前准备数据比较容易。 稍后让您的代码更简单。

这是我会做的,创建非标点符号名称反向散列到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"; 
    } 
} 
+0

这给了我一个伟大的想法,我的价值分配到一个临时散列和修改一个,同时还返还原物。 @rouzier – JDE876 2015-02-23 22:07:34

+0

一些常规提示,请使用'use strict;'和'use warnings;'。并使用open的三个参数版本,包含词法文件句柄和正确的错误处理'open my $ filehandle,'<',$ filename或者'Can not read'$ filename':$!“;' – dgw 2015-02-23 22:32:46

+0

此外'while'可以是写得更紧凑'while(my $ line = <$fh>){'。 – dgw 2015-02-23 22:33:56