首页 > 解决方案 > 从不正确的输入中预测 JavaScript 字符串

问题描述

我目前正在编写一个 Discord 机器人,并且想知道如果输入不正确,是否可以预测想要的命令。

例如,我有这个单词列表: ['help','meme','ping'],如果用户输入“ hepl”,是否有可能以某种方式“猜测”他们想要输入的内容help

标签: javascriptalgorithmbotsdiscord.jsprediction

解决方案


一种选择是找到一个与输入的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 只是一个数字,请随意选择您想要的容差——它越高,猜到的命令越多,但误报越多)


推荐阅读