2015-02-23 44 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