2

我正在使用同义词列表来指导查询扩展过程。格式如下所示:

fu=foo
ba=bar
etc=etcetera
werd=word

我正在使用一个简单的二进制搜索算法来针对这个列表运行每个用户输入的单词。问题是,在使用短语时。

    quick brown fox=alphabet
    out of this world=space
    why hello there=hello

典型输入:why hello there, where can I get an out of this world hopper?

所需的输出是:hello, where can I get an space hopper?

我也不想运行每个单词对或三次搜索,并且我想避免对输入的词库列表进行线性搜索,因为这是低效的(尽管列表应该很小,所以这是一个选项)。

因此,我正在寻找对短语运行二进制搜索的方法,或者以补偿短语的方式构建词库。

我为此使用PHP。欢迎提出任何建议。

4

3 回答 3

2

简单的方法是使用str_replace。不过我不知道性能如何。

$list = array('out of this world' => 'space');
$str = 'why hello there, where can I get an out of this world hopper?';

foreach ($list as $old => $new) {
    $str = str_replace($old, $new, $str);
}

编辑:我经常注意到使用内置函数而不是编写自己的函数更有效,因为内置函数已经编译,但需要解释优化的算法,这会大大降低速度。

于 2011-12-01T22:52:25.930 回答
1

我的第一个想法是使用这样的关联数组

$thesaurus = array(
   'alphabet'  => 'quick brown fox',
   'space'     => 'out of this world',
   'hello'     => 'why hello there'
);

这样你就可以使用内置的 array_search 函数,这将比你用 PHP 编写的任何东西都快(我认为)。

于 2011-12-01T22:47:58.143 回答
1

使用preg_replace_callback而不是您现在所做的任何事情。PCRE 恰好在字符串搜索方面非常有效,因为这就是它的用途。

您只需要构建一个替代列表,然后通过回调中的原始地图/字典进行实际替换。

$phrases = array(...);

$rx = implode("|", array_keys($phrases));
$text = preg_replace("/\b($rx)\b/musie", '$phrases["\1"]', $text);

在这里只使用一个/e表达式,回调可能会更有用。

于 2011-12-01T22:48:13.853 回答