[英]How do I implement NodeJS “Did you mean” feature?
How can I implement a "Did you mean" feature in NodeJS?如何在 NodeJS 中实现“您的意思是”功能? I searched the internet and found a tutorial that uses a webserver but I will be using this for a Discord bot, so I can't really use tutorials that involve web servers, etc.
我在互联网上搜索并找到了一个使用网络服务器的教程,但我将把它用于 Discord 机器人,所以我不能真正使用涉及 web 服务器等的教程。
For example:例如:
User enters command: restrat
Actual command: restart
Bot Message: Command not found, did you mean "restart"?
Is this possible using NodeJS?这可能使用NodeJS吗? If so, may I know how I can implement this?
如果是这样,我可以知道如何实现吗?
Any help will be greatly appreciated.任何帮助将不胜感激。 Thanks.
谢谢。
Whether in NodeJS or the browser, some code is needed to find a command that most closely resembles the text entered by the user.无论是在 NodeJS 中还是在浏览器中,都需要一些代码来找到与用户输入的文本最相似的命令。
This code uses the Levenshtein distance calculation to return the closest match.此代码使用Levenshtein 距离计算来返回最接近的匹配。
const jsLevenshtein = require("js-levenshtein");
function closestCommand (userText, commands) {
let minDistance = Infinity;
return commands.reduce((closest, cmd) => {
const cmdDistance = jsLevenshtein(userText, cmd);
if (cmdDistance < minDistance) {
minDistance = cmdDistance;
return cmd;
}
return closest;
}, '');
}
const myCommands = ['quit', 'login', 'logout', 'restart', 'refresh'];
const userCommand = 'restrat';
console.log(`closest command is '${closestCommand(userCommand, myCommands)}'`);
// closest command is 'restart'
Working code in RunKit. RunKit 中的工作代码。
It should be straightforward to add this to a NodeJS app.将它添加到 NodeJS 应用程序应该很简单。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.