作者liyih ()
看板Perl
标题Re: [问题] 计算两个中文字间的最小距离
时间Sun Jun 14 02:29:11 2009
※ 引述《dorwell (这真的是很神奇~~)》之铭言:
: 想请问板上的高手~
: 请问有没有比较快的方法可以计算两个字间的最短距离(linux指令处理也可以)
: 例如: 火车快飞火车快飞,飞过高山
: 火车和高山的最短距离为5
: 谢谢
想法是考虑以下两种可能
左 distance 右
1. substr1 ... substr2
2. substr2 ... substr1
用 regexp 来取代 index() 计算比对,使用 .*? 来取得最小的右边界,
而用 $substr1[^\b$substr1\b] 来取得最大的左边界,match 到的就是
两字串间的最短距离。这想法只是初略的概念,或许还有较正确或更快的
方式,您可以参考看看。
------------------------------------------------------------------------------
#!/usr/bin/perl -w
#
use strict;
use warnings;
#
use Encode;
my $str = decode("utf-8", "火车快飞火车快飞,飞过高山");
#my $str = decode("utf-8", "火车快飞火车快飞,飞过高山高山");
#my $str = decode("utf-8", "火车快飞火车快飞,飞过高山高山"x10000000);
my @parts = (decode("utf-8", "火车"),
decode("utf-8", "高山"),
);
if ($str =~ m/$parts[0]([^\b$parts[0]\b]*?)$parts[1]/) {
print "Case 1: ", length($1), " => ", encode("utf-8", $1), "\n";
}
if ($str =~ m/$parts[1]([^\b$parts[1]\b]*?)$parts[0]/) {
print "Case 2: ", length($1), " => ", encode("utf-8", $1), "\n";
}
-------------------------------------------------------------------------
Case 1: A----BA__B => 2
Case 2: A__BA----B => 2
Case 3: A--A_B---B => 1
my @matches = ();
if (@matches = ($str =~ m/$parts[0]([^\b$parts[0]\b]*?)$parts[1]/g)) {
for (@matches) {
print "Case 1: ", length($_), " => ", encode("utf-8", $_), "\n";
}
}
if (@matches = ($str =~ m/$parts[1]([^\b$parts[1]\b]*?)$parts[0]/g)) {
for (@matches) {
print "Case 2: ", length($_), " => ", encode("utf-8", $_), "\n";
}
}
--
※ 发信站: 批踢踢实业坊(ptt.cc)
◆ From: 59.104.150.240
※ 编辑: liyih 来自: 211.74.245.31 (06/15 19:50)
1F:推 dorwell:已经解决问题了~有点晚推文不好意思~感谢高手的帮忙 06/17 21:50