我想在Javascript中进行基本的AI聊天。
1)如果用户说'嗨,我的名字是Thore',我想检查一些预定值最接近的匹配。
我的数组看起来像这样:
const nameSentences = [`my name is`, `i'm`, `they call me`];如何查看最接近的匹配? 在这个例子中,它应该是我的数组的第一个值。
2)第二部分是我如何从用户输入中获取名称。 是否可以预定义变量应该站立的位置?
像这样的东西
const nameSentences = [`my name is ${varName}`, `i'm ${varName}`, `they call me ${varName}`];然后使用用户输入将匹配句子子串,以保存变量的名称?
I want to make a basic AI chat in Javascript.
1) If a user says 'Hi, my name is Thore' I want to check what the closest match is with some predefined values.
My array looks like this:
const nameSentences = [`my name is`, `i'm`, `they call me`];How can I check what the closest match is? In this example it should be the first value of my array.
2) The second part is how I can get the name out of the user input. Is it possible to predefine a place where the variable should stand?
Something like this
const nameSentences = [`my name is ${varName}`, `i'm ${varName}`, `they call me ${varName}`];And afterwards substring the matching sentence with the user input to save the name the variable?
最满意答案
您可以将您希望接受名称的不同方式保存为正则表达式,并在正则表达式中捕获名称。 您可以随心所欲地使用它,但这是一个起点。
找到匹配后,您可以停止迭代可能的变体,您可以获取匹配并输出名称。
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`));You can save the different ways you would like to accept a name as Regular Expressions, with the capture for the name in the regular expression. You can get as robust as you'd like with it, but here is a starting point.
Once you find a match, you can stop iterating over the possible variations, you can take the match and output the name.
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`));
更多推荐
发布评论