【发布时间】:2012-07-30 07:19:18
【问题描述】:
我正在为我的一个项目使用 JavaScript 开发客户端搜索系统,并且在让搜索功能按预期运行时遇到了特别麻烦。
目前,搜索词在数组q 中排序并用for 循环循环(所以q[i] 是当前正在处理的词),选择它们所属的词,然后也不会互相影响。
这会导致两个问题。
对于第一个问题,搜索 intro 会返回一篇 Introduction 文章,如您所料,但类似地搜索 con em> 返回一篇关于 Conditions 的文章,这并不是真正有用的功能。
第二个更严重的问题是搜索词不会相互影响,因此搜索
introduction is important for comedians to setup their jokes会返回“介绍”和“设置”文章,因为这些词在查询中。
代码 sn-p 循环遍历每个搜索词(在循环每篇文章的循环内)并确定结果的优先级,如下所示:
rq = new RegExp(q[i], 'gim');
eq = new RegExp("\\b" + escape(q[i]) + "\\b", 'gi');
if (rq.test(title) || rq.test(keywords)) {
match = true;
if (title.match(rq) != null) {
if (title.match(eq) != null) {
priority += (title.match(eq).length * 5)
}
priority += (title.match(rq).length); // Is this wise?
}
if (keywords.match(rq) != null) {
if (keywords.match(eq) != null) {
priority += (keywords.match(eq).length * 3);
}
priority += (keywords.match(rq).length); // Is this wise?
}
}
这些行为在算法决策中是不可避免的,但是我根本想不出更好的方法来做到这一点(而且显然有更好的方法)。 可能是我想多了。
【问题讨论】:
标签: javascript regex algorithm search