gpt4 book ai didi

javascript - Discord.js 搜索关键词

转载 作者:行者123 更新时间:2023-11-30 20:04:24 24 4
gpt4 key购买 nike

我正在尝试创建一个用于在某些游戏中进行交易的 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
});
}

我是 Javascript 的新手,所以我不太确定如何让它工作。感谢任何提示,谢谢!

最佳答案

看起来您要实现的是一种称为模糊搜索 的机制,用户可以使用拼写错误或近似字符串找到相似的结果。

(引用:https://en.wikipedia.org/wiki/Approximate_string_matching)

这对于编程初学者来说并不是一个容易实现的功能,要么数据库必须支持某种模糊查询,要么你必须先从数据库中获取所有数据,然后使用 JavaScript 模糊查询搜索库来实现这一点。

如果你还想这样做,我建议使用 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 是如何实现的,这里有一些有用的链接

关于javascript - Discord.js 搜索关键词,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53065747/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com