我正在尝试创建一个Discord机器人以在某些游戏中进行交易。到目前为止,我已经使用了大多数基本命令-!create在SQL数据库中创建交易清单,!find找到一个-但是只能在完全相同的单词上找到它。我想做的是使搜索不太具体,因此这些术语不必完全等于显示结果。 我当前的代码非常复杂,不用说,它很破损:
var searchTerms = args[1].split(" ");
var output = {};
for (var id in userData) {
for (var offer in userData[id].offers) {
var score = 0;
for (var key in searchTerms) {
if (offer.includes(key)) {
score ++;
}
}
if (score >= searchTerms.length / 2) {
output[id] = userData[id].offers[offer] + " - " + ((score / searchTerms.length) * 100) + "%";
}
}
}
if (output == {}) {
bot.sendMessage({
to: channelID,
message: 'No matching offers found.'
});
} else {
msg = ""
for (id in output) {
msg += '<@' + id + '> - ' + output[id] + " "
}
bot.sendMessage({
to: channelID,
message: Object.keys(output).length + ' offers found: ' + msg
});
}
我是Java的新手,所以我不确定如何使它正常工作。任何提示表示赞赏,谢谢!
答案 0 :(得分:1)
您似乎要实现的机制叫Fuzzy Search
,用户可以使用错字或近似字符串找到类似的结果。
(参考:https://en.wikipedia.org/wiki/Approximate_string_matching)
对于编程初学者来说,这并不是一个容易实现的简单功能,要么数据库必须支持某种模糊查询,要么您必须首先从数据库中获取所有数据,然后使用JavaScript Fuzzy搜索库就可以做到这一点。
如果您仍然想这样做,我建议使用Fuse.js,它可以在几行中完成模糊搜索
//list to be searched
var books = [{
'ISBN': 'A',
'title': "Old Man's War",
'author': 'John Scalzi'
}, {
'ISBN': 'B',
'title': 'The Lock Artist',
'author': 'Steve Hamilton'
}]
// init the search
var options = {
keys: ['title', 'author'],
id: 'ISBN'
}
var fuse = new Fuse(books, options)
fuse.search('old')
// result
[
"A"
]
模糊搜索是一个复杂的计算机科学问题,如果您想进一步了解它以及如何实现Fuse.js,这里有一些有用的链接