[英]Discord.js searching on key terms
我正在嘗試創建一個 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 的新手,所以我不確定如何讓它工作。 任何提示表示贊賞,謝謝!
看起來您要實現的是一種稱為Fuzzy Search
的機制,用戶可以使用拼寫錯誤或近似字符串找到類似的結果。
(參考: 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 是如何實現的,這里有一些有用的鏈接
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.