如何在GATE JAPE规则Java RHS中获取句子内注解的Feature Map
扩展GATE Jape规则:提取Sentence内注解特征并生成新注解
你想要实现的是基于已有的Sentence注解,提取它内部所有带majorType、string、type特征的Lookup注解,然后生成一个新的Sentence contains注解,把这些被包含注解的特征都整合进去对吧?我来帮你一步步调整Jape规则,实现这个需求。
首先,你之前尝试的LHS写法有点小问题,我们需要先绑定整个Sentence,再指定它包含的目标注解集合,这样在RHS里才能准确获取到所有符合条件的注解。
完整的Jape规则实现
Phase: SentenceContainsAnnotations Input: Sentence Lookup Options: control = all Rule: ExtractSentenceContainedAnnotations ( {Sentence} :sentence {Lookup.majorType != null, Lookup.string != null, Lookup.type != null} containedWithin :sentence ) -> { // 获取绑定的Sentence注解 gate.Annotation sentenceAnn = (gate.Annotation)bindings.get("sentence"); // 获取Sentence范围内所有符合条件的Lookup注解集合 gate.AnnotationSet containedLookups = (gate.AnnotationSet)bindings.get("containedWithin"); // 创建新注解的Feature Map gate.FeatureMap newFeatures = gate.Factory.newFeatureMap(); // 遍历所有被包含的Lookup注解,收集它们的特征 int count = 0; for(gate.Annotation lookup : containedLookups) { gate.FeatureMap lookupFeatures = lookup.getFeatures(); // 为每个Lookup注解的特征创建唯一的键,避免冲突 newFeatures.put("lookup_" + count + "_majorType", lookupFeatures.get("majorType")); newFeatures.put("lookup_" + count + "_string", lookupFeatures.get("string")); newFeatures.put("lookup_" + count + "_type", lookupFeatures.get("type")); count++; } // 添加注解数量特征,方便后续处理 newFeatures.put("contained_lookup_count", count); newFeatures.put("rule", "ExtractSentenceContainedAnnotations"); // 生成新的"Sentence contains"注解,范围与原Sentence一致 outputAS.add(sentenceAnn.getStartNode(), sentenceAnn.getEndNode(), "Sentence contains", newFeatures); }
关键细节说明
- LHS部分:先绑定
Sentence为:sentence,再用containedWithin :sentence指定所有符合特征非空条件的Lookup注解都在这个Sentence范围内,这样containedWithin会绑定所有符合要求的Lookup注解集合。如果不需要过滤空特征,把Lookup的条件改成{Lookup}即可。 - RHS部分:
- 先获取绑定的Sentence注解和所有被包含的Lookup注解集合
- 遍历每个Lookup注解,用
lookup_序号_特征名的格式存储特征,避免键名冲突 - 最终生成的
Sentence contains注解和原Sentence的起止位置完全一致,特征里整合了所有被包含注解的信息
可选优化:用列表存储特征
如果你希望更方便地批量处理特征,可以把所有Lookup的特征以列表形式存入Feature Map:
// 用List存储每个Lookup的特征Map java.util.List<gate.FeatureMap> lookupFeatureList = new java.util.ArrayList<>(); for(gate.Annotation lookup : containedLookups) { lookupFeatureList.add(lookup.getFeatures()); } newFeatures.put("contained_lookups", lookupFeatureList);
这样新注解的contained_lookups特征就是一个包含所有Lookup特征Map的列表,后续处理起来会更灵活。
内容的提问来源于stack exchange,提问作者FJ1993
相关产品推荐
相关产品推荐

