javascript - 从不正确的输入中预测 JavaScript 字符串
问题描述
我目前正在编写一个 Discord 机器人,并且想知道如果输入不正确,是否可以预测想要的命令。
例如,我有这个单词列表:
['help','meme','ping']
,如果用户输入“ hepl
”,是否有可能以某种方式“猜测”他们想要输入的内容help
?
解决方案
一种选择是找到一个与输入的levenshtein 距离为 2 或更小的命令:
// https://gist.github.com/andrei-m/982927
const getEditDistance=function(t,n){if(0==t.length)return n.length;if(0==n.length)return t.length;var e,h,r=[];for(e=0;e<=n.length;e++)r[e]=[e];for(h=0;h<=t.length;h++)r[0][h]=h;for(e=1;e<=n.length;e++)for(h=1;h<=t.length;h++)n.charAt(e-1)==t.charAt(h-1)?r[e][h]=r[e-1][h-1]:r[e][h]=Math.min(r[e-1][h-1]+1,Math.min(r[e][h-1]+1,r[e-1][h]+1));return r[n.length][t.length]};
const commands = ['help','meme','ping'];
const getCommand = (input) => {
if (commands.includes(input)) return input;
return commands.find(command => getEditDistance(input, command) <= 2);
};
console.log(getCommand('hepl'));
(2 只是一个数字,请随意选择您想要的容差——它越高,猜到的命令越多,但误报越多)
推荐阅读
- python-3.x - 如何捕获行的块
- php - 如何在 symfony5 应用程序中使用 cdn 并编写正确的 webpack encore 配置
- api - 使用谷歌视觉进行 OCR 的正确方法是什么
- java - 从字符串中获取第一个可打印字符
- svg - 是否可以创建 Html 标签将遵循 svg 路径动画的动画?
- javascript - 使用 Nunjucks 获取 Eleventy 的当前月份?
- java - Spring boot - J2EE 不良做法:存储在会话中的不可序列化对象
- firebase - 如何两次过滤来自 Cloud Firestore 的数据?
- python-3.x - 在 Python 工作流中访问 Github Secrets
- java - Eclipse 提交错误 svn:E204900:无法创建目录