我想用Javascript创建一个基础的AI聊天程序。
1) 如果用户说“嗨,我的名字是托尔”,我想检查与一些预定义值最接近的匹配是什么。
我的数组看起来像这样:
const nameSentences = [`my name is`, `i'm`, `they call me`];
我怎样才能检查什么是最接近的匹配?在这个例子中,应该是我的数组的第一个值。
2) 第二部分是如何从用户输入中提取名字。是否可以预定义一个变量应该站的位置?
像这样
const nameSentences = [`my name is ${varName}`, `i'm ${varName}`, `they call me ${varName}`];
然后将匹配的句子与用户输入进行子字符串处理以保存变量中的名字?
回答:
您可以将接受名字的不同方式保存为正则表达式,并在正则表达式中捕获名字。您可以根据需要使其尽可能健壮,但这里是一个起点。
一旦找到匹配,您可以停止迭代可能的变体,取出匹配并输出名字。
const nameSentences = [ /i'm (\w+)/i, /my name is (\w+)/i, /they call me (\w+)/i];function learnName(input) { let match; for (let i = 0; i < nameSentences.length; i++) { match = input.match(nameSentences[i]); if (match) break; } if (match) { return `Hello, ${match[1]}. It's nice to meet you.`; } else { return `I didn't catch that, would you mind telling me your name again?`; }}console.log(learnName('Hi, my name is Thore.'));console.log(learnName('They call me Bob.'));console.log(learnName(`I'm Joe.`));console.log(learnName(`Gibberish`));