use edit distance on arrays in perl

2019-07-07 16:45发布

问题:

I am attempting to compare the edit distance between two arrays. I have tried using Text:Levenshtein.

#!/usr/bin/perl -w
use strict;
use Text::Levenshtein qw(distance);

my @words = qw(four foo bar);
my @list = qw(foo fear);
my @distances = distance(@list, @words);

print "@distances\n";
#results: 3 2 0 3

I however want the results to appear as follows:

2 0 3
2 3 2

Taking the first element of @list through the array of @words and doing the same through out the rest of the elements of @list. I plan on upscaling this to a much larger arrays.

回答1:

I'm not sure to understand exactly what you meant, but I think this is what you expect :

#!/usr/bin/perl -w
use strict;
use Text::Levenshtein qw(distance);

my @words = qw(four foo bar);
my @list = qw(foo fear);

foreach my $word (@list) {
   my @distances = distance($word, @words);
   print "@distances\n";
}


回答2:

Taking the first element of @list through the array of @words and doing the same through out the rest of the elements of @list.

You just described exactly what you need to do to get the output you would like; loop through the @list array and for each element compute the distance for all elements of the @words array.