了解斯坦福大学核心NLP令牌正则表达式语法,用于任意短语匹配



所以我最近一直在使用 NLP,除了像/test/这样非常简单的匹配之外,我在使用他们的正则表达式语法时遇到了麻烦。我正在寻找的最终游戏是匹配在其内容中的某处包含特定单词的短语。我试图建模的语音模式是非常结构化的,但是,因为人类的语音是可变的,这些短语可以开始无数种方式,但只要短语包含某些关键字,我就想计算它。因此,作为一个例子,我尝试在TokensRegex中建模的正则表达式是:

.*(show).*(cars).*(d{0,9})(km|mi).*

这将匹配以下短语:

"please show me all cars within 100 km of me"

从他们的文档中,我看不出可以构造一个复杂的短语。如果可以的话,我很难看到如何将其转换为他们的语法。我最接近的似乎是这样的:

"[]*/(show)/[]*/(cars)/[]*[word>=0]/(kilometer|miles)/[]"

这是我用来检查匹配项的代码片段:

//value is the regex, tokens is the List<CoreLabel>s of text to try and match
pattern = TokenSequencePattern.compile(value);
TokenSequenceMatcher matcher = pattern.getMatcher(tokens);
while (matcher.find()) {
String matchedString = matcher.group();
System.out.println(matchedString);
return true;
}

当我调试它时,我看到匹配器内的元素是核心标签列表

(show,me,all,cars,within,a,hundred,kilometers,of,me) 

并将模式编译成序列模式列表

(*,TextAnnotation:/show/,*,TextAnnotation:/cars/,*,TextAnnotation GE 0.0, TextAnnotation:/(kilometer[s]?|mile[s]?)/,*)

对我来说,这似乎应该匹配,但事实并非如此。甚至像这样剥离的东西:

show me all cars

使用正则表达式:

[]/show/[]/cars/[]

不匹配,所以它让我倾向于不设置正则表达式。关于 TokensRegex 的局限性,我有什么不了解的,或者我没有正确构造表达式。任何帮助将不胜感激,谢谢!

事实证明,我不需要直接使用TokensRegex来解决我的问题。我试图解决的关键是挑选短语中的数字并转换它们,但我意识到我可以使用 CoreNLP 的 NERClassifierCombiner 来挑选它们,替换它们,并使用普通正则表达式来匹配更新的输入短语。我所做的示例如下,对于"向我显示 15 公里内的所有汽车"等短语,这会将其转换为"向我显示 15 公里内的所有汽车":

Sentence sentence = new Sentence(eventName);
String serializedClassifier = "english.muc.7class.distsim.crf.ser.gz";
NERClassifierCombiner combiner = null;
try {
combiner = new NERClassifierCombiner(serializedClassifier);
} catch (IOException e) {
e.printStackTrace();
}
List<String> reconstructedEventTokens = new ArrayList<>();
for (CoreLabel cl : combiner.classify(sentence.asCoreLabels())) {
if(cl.ner() == KBPRelationExtractor.NERTag.NUMBER.name){
reconstructedEventTokens.add(cl.get(CoreAnnotations.NumericCompositeValueAnnotation.class).toString());
}else{
reconstructedEventTokens.add(cl.originalText());
}
}
String newEvent = String.join(" ",reconstructedEventTokens);
System.out.println("matching phrase to check: "+newEvent);
Pattern pattern = Pattern.compile(value);
Matcher matcher = pattern.matcher(newEvent);

花了更多的挖掘库来找到NER工具包,但它现在就像一个魅力!希望这有助于其他人试图在他们的短语中查找数字或其他实体。

相关内容

最新更新