gpt4 book ai didi

javascript - 匹配大量不同的句子(使用正则表达式模式解析)

转载 作者:行者123 更新时间:2023-11-29 10:56:14 25 4
gpt4 key购买 nike

我想使用正则表达式构建一个文本句子分类器(用于聊天机器人自然语言处理)。

我有大量(例如 >> 100)不同类型的文本句子来匹配正则表达式模式。

当一个句子匹配一个正则表达式(比如,一个意图)时,激活一个特定的 Action (一个函数处理程序)。

我预设了特定的正则表达式来匹配任何不同的句子集,例如:

     // I have a long list of regexps (also many regexp for a many intents)

const regexps = [
/from (?<fromCity>.+)/, // ---> actionOne()
/to (?<toCity>.+)/, // ---> actionTwo()
/.../, // ---> anotherAction()
/.../ // ---> yetAnotherAction()
]

// I have a long list of actions (function handlers)

const actions = [
actionOne(),
actionTwo(),
...,
...
]

如何构建最快的(多正则表达式)分类器(在 Javascript 中)?

我目前快速而肮脏的解决方案是按顺序检查每个正则表达式:

    // at run time        
...
sentence = 'from Genova'
...

if (sentence.match(/from (?<fromCity>.+)/)
actionOne()

else if(sentence.match(/to (?<toCity>.+)/)
actionTwo()

else if ...
else if ...
else
fallback()

上述 if-then 序列 方法的可扩展性不高,最重要的是在性能方面很慢(即使大多数频繁使用的正则表达式排序可能有所帮助)。

另一种提高性能的方法可能是:创建一个单个(大)正则表达式,由命名组(每个匹配器-正则表达式一个)交替组成

在最小的例子中:

   const regexp = /(?<one>from (?<toCity>.+))|(?<two>to (?<toCity>.+))/

所以我简单地创建了正则表达式分类器(请将下面的代码作为 javascript 伪代码):

    // at build time

// I collect all possible regexps, each one as a named group
const intents = [
'(?<one>from (?<fromCity>.+))',
'(?<two>to (?<toCity>.+))',
'...',
'...'
]

const classifier = new RegExp(intents.join('|'))

// collection of functions handlers, one for each regexp
const Actions = {
'one': 'actionOne',
'two': 'actionTwo',
...,
...
}

// at run time

const match = sentence.match(classifier)

// if match, call corresponding function handler
// match.groups contains the matching named group
const action = Actions[match.groups]

if ( action )
action()
else
fallback() // no match

有意义吗?对更好的方法有什么建议吗?

最佳答案

这很可能取决于许多因素,例如每个单独的 RegExp(例如,有多少捕获组)、列表的实际大小和输入的长度。

但是当测试非常大量的 RegExp(10000 个简单的)时,大组合 RegExp 的任何变化都比一个接一个地执行单个 RegExp 慢得多。 JSPerf

考虑到这些信息,以及它总体上使代码更简单的事实,我建议不要采用那种大的 RegExp 方法。

为了使事情更容易维护,我建议将每个触发器及其操作存储在同一个地方,例如一个对象数组。如果需要,这还可以让您稍后向这些对象添加更多内容(例如命名意图):

const intents = [
{ regexp: /from (?<fromCity>.+)/, action: fromCity },
{ regexp: /to (?<toCity>.+)/, action: toCity },
{ regexp: /.../, action: anotherAction },
];

// We use find to stop as soon as we've got a result
let result = intents.find(intent => {
let match = sentence.match(intent.regexp);
if (match) {
// You can include a default action in case the action is not specified in the intent object
// Decide what you send to your action function here
(match.action || defaultAction)(match, sentence, intent);
}
return match;
});
if (!result) {
fallback();
}

关于javascript - 匹配大量不同的句子(使用正则表达式模式解析),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56616635/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com