这是一个 Perl 6 解决方案。尽管有插页式的东西,我使用的语法知道如何抓取四个有趣的字符。更复杂的要求需要不同的语法,但这并不难。
每次匹配时,NString::Actions 类对象都会更改以检查匹配。它和我之前做的一样高水位标记。这看起来像是更多的工作,它是为了这个简单的例子。对于更复杂的示例,情况不会更糟。我的 Perl 5 版本必须使用大量工具来确定要保留或不保留的内容。
use Text::Levenshtein;
my $string = 'The quixotic purple and jasmine butterfly flew over the quick zany dog';
grammar NString {
regex n-chars { [<.ignore-chars>* \w]**4 }
regex ignore-chars { \s }
}
class NString::Actions {
# See
my subset IntInf where Int:D | Inf;
has $.target;
has Str $.closest is rw = '';
has IntInf $.closest-distance is rw = Inf;
method n-chars ($/) {
my $string = $/.subst: /\s+/, '', :g;
my $distance = distance( $string, self.target );
# say "Matched <$/>. Distance for $string is $distance";
if $distance < self.closest-distance {
self.closest = $string;
self.closest-distance = $distance;
}
}
}
my $action = NString::Actions.new: target => 'Perl';
loop {
state $from = 0;
my $match = NString.subparse(
$string,
:rule('n-chars'),
:actions($action),
:c($from)
);
last unless ?$match;
$from++;
}
say "Shortest is { $action.closest } with { $action.closest-distance }";
(我从 Perl 5 做了一个直接移植,我将在这里留下)
我在 Perl 6 中尝试过同样的事情,但我确信这有点冗长。我想知道是否有一种聪明的方法可以抓取 N 个字符组进行比较。也许我以后会有一些改进。
use Text::Levenshtein;
put edit( "four", "foar" );
put edit( "four", "noise fo or blur" );
sub edit ( Str:D $start, Str:D $target --> Int:D ) {
my $target-modified = $target.subst: rx/\s+/, '', :g;
my $last-position-to-check = [-] map { .chars }, $target-modified, $start;
my $closest = Any;
my $closest-distance = $start.chars + 1;
for 0..$last-position-to-check -> $starting-pos {
my $substr = $target-modified.substr: $starting-pos, $start.chars;
my $this-distance = distance( $start, $substr );
put "So far: $substr -> $this-distance";
if $this-distance < $closest-distance {
$closest = $substr;
$closest-distance = $this-distance;
}
last if $this-distance = 0;
}
return $closest-distance // -1;
}