これはほとんど機能します:
#!/usr/bin/env perl
use strict;
use warnings;
my $tok = undef;
my @pairs = ();
my $looking_for = 'surname';
sub parse_line_to_words($){
my $l = shift;
my @words;
my $word = '';
my $start = 1;
# remove trailing newlines
chomp $l;
if(index($l, '"', -1) != -1){
# remove trailing quotation mark.
chop $l;
}
foreach my $c (split//,$l){
if($c eq '"'){
if($#words == -1){
# skip leading quotation marks
next;
}
}
if($c eq ','){
push(@words, $word);
$word = '';
$start = 1;
} else{
if($start && $c eq ' '){
next;
} else{
$start = 0;
}
$word .= $c;
}
}
if($word ne ''){
push(@words, $word);
}
return @words;
}
sub peek_and(@){
foreach my $word (@_){
return 1 if $word eq 'and'
}
return 0;
}
sub split_and(@){
my @copy;
foreach my $word (@_){
if(index($word, 'and ', 0) != -1){
my $i = index($word, 'and ', 0) + 4;
push(@copy, substr($word, 0, $i - 1));
push(@copy, substr($word, $i));
} else{
push(@copy, $word);
}
}
return @copy;
}
sub count_spaces($){
my $w = shift;
my $s=0;
for(my $p = index($w, ' ', 0); $p != -1; $p=index($w, ' ', $p+1), $s++) {}
return $s;
}
sub found($$$){
my $pairs = shift;
push(@{$pairs}, {'surname' => shift, 'firstname' => shift});
}
while(<>){
chomp;
my $line = $_;
my @words = parse_line_to_words($line);
@words = split_and(@words);
my $line_has_and = peek_and(@words);
foreach my $word (@words){
my $spaces = count_spaces($word);
if($looking_for eq 'surname'){
if(index($word, '.', -1) != -1 && $spaces == 0){
# looks like an initial to me, skip it
} else{
if($spaces > 0){
# multi-word token; must be corporation name
my($f, $l) = split(/ /, $word);
found(\@pairs, $f, $l);
} else{
$tok = $word;
$looking_for = 'firstname';
}
}
} elsif ($looking_for eq 'firstname'){
if($line_has_and){
# lastname, first1, ..., firstn and firstn+1
if($word ne 'and'){
found(\@pairs, $tok, $word);
}
} else{
# lastname, f. or lastname, firstname
found(\@pairs, $tok, $word);
$looking_for = 'surname';
}
}
}
$looking_for = 'surname'; # reset for new line
}
foreach my $p (@pairs){
printf("%s\t%s\n", $p->{'surname'}, $p->{'firstname'});
}
特定のサンプル入力の実際の出力
Acme Corporation
John Doe
Smith Allen
Smith Susan
Marshall J.
Johnson H.
Caruso D.
Jones J.
Stein Harry
Stein Joan
Stein Mike
討論
次のヒューリスティックを採用しました。
- 行の先頭と末尾の引用符は無視する必要があります。
- 各行は、一連のコンマ区切り値として単語にトークン化できます。
- 単語がスペース文字で始まる場合、それらの文字は無視する必要があります。
- 単語のペアの最初の単語は名前で、2番目の単語は名前です(特別な場合を除く)。
- 行の単語が'および'で始まる場合は、行全体を特別に処理する必要があります。最初の単語は名前で、残りは対応する名です。
- 姓のスペースが0を超える場合は、会社の名前です。
- 会社名は常にスペースで区切られた2つの単語であり、それぞれ名前と名として扱う必要があります。
- 非法人名にはスペースは含まれません。
結局、私は「正規表現」を使用して、企業名をスペースで分割するだけでした。これは、正規表現以外のバージョンに簡単に置き換えることができます。
これらすべてを使用しても、入力で名前が逆になっているため、「JohnDoe」が間違っています。私はこれを検出するための信頼できる方法を考案することができませんでした。