根据不正确的输入预测 JavaScript 字符串

Predict JavaScript string from incorect input

我目前正在编写 Discord 机器人程序,想知道如果输入不正确是否可以预测所需的命令。

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

一个选项是从输入中找到 levenshtein distance 等于或小于 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只是一个数字,随意选择你想要的公差 - 它越高,猜测的命令越多,但误报越多)

您可以找到匹配项并在建议中显示很多词。如果你想要同样的,你可以使用显示最热门的词。

const words = ["help", "meme", "ping"];
const getHits = (word, wordToMatch, hits = 0) => {
  if (!word.length || !wordToMatch.length) return hits;
  let charW = word.slice(0, 1);
  let index = wordToMatch.indexOf(charW);
  if (index !== -1) {
    return getHits(
      word.slice(1),
      String(wordToMatch.slice(0, index) + wordToMatch.substr(index + 1)),
      hits + 1
    );
  }
  return getHits(word.slice(1), wordToMatch, hits);
};
const getMatch = mword => {
  return words.reduce((m, word) => {
    m[word] = getHits(mword, word);
    return m;
  }, {});
};
const sort = obj => {
  return Object.entries(obj).sort(
    ([_, value1], [__, value2]) => value2 - value1
  );
};
console.log(getMatch("help"));
console.log(sort(getMatch("help")));

console.log(getMatch("me"));
console.log(sort(getMatch("me")));
.as-console-row {color: blue!important}