You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Flutter中实现vaModel列表的无序多关键词全匹配方法

Flutter无序多关键词全匹配实现方案

1. 输入预处理

先将用户输入的句子标准化为单词列表,处理大小写、标点符号,避免格式差异导致匹配失败:

List<String> processUserInput(String input) {
  // 转小写、去除标点、拆分单词并过滤空字符串
  final cleanedInput = input.toLowerCase().replaceAll(RegExp(r'[^\w\s]'), '').trim();
  return cleanedInput.split(RegExp(r'\s+')).where((word) => word.isNotEmpty).toList();
}

2. 核心匹配逻辑

把预处理后的用户单词转成Set提升查找效率,遍历vaData列表,检查每个vaModel的所有关键词是否都包含在用户输入的单词集合中:

String? findMatchingResponse(List<String> userWords) {
  final userWordSet = Set<String>.from(userWords);
  
  for (final model in vaData) {
    // 验证当前模型的所有关键词是否都在用户输入里
    bool allKeywordsMatch = model.stringData.every((keyword) => userWordSet.contains(keyword));
    if (allKeywordsMatch) {
      return model.response; // 返回第一个匹配的结果
    }
  }
  
  return null; // 无匹配时返回null
}

3. 完整调用示例

结合预处理和匹配逻辑,完整调用流程如下:

void main() {
  String userInput = "what my score is for this lecture";
  List<String> processedWords = processUserInput(userInput);
  String? response = findMatchingResponse(processedWords);
  
  print(response); // 输出: load1
}

4. 优化建议

  • 预转换集合:提前将vaModel的stringData转成Set,避免每次匹配重复转换,提升性能:

    class vaModel {
      final int id;
      final List<String> stringData;
      final Set<String> stringDataSet;
      final String response;
    
      vaModel({
        required this.id,
        required this.stringData,
        required this.response,
      }) : stringDataSet = Set<String>.from(stringData);
    }
    

    匹配时直接用userWordSet.containsAll(model.stringDataSet),代码更简洁高效。

  • 过滤停用词:忽略用户输入中的无意义虚词(如is、for、this),预处理阶段加入过滤逻辑:

    final stopWords = {'is', 'for', 'this', 'the', 'a', 'an'};
    
    List<String> processUserInput(String input) {
      final cleanedInput = input.toLowerCase().replaceAll(RegExp(r'[^\w\s]'), '').trim();
      return cleanedInput.split(RegExp(r'\s+'))
          .where((word) => word.isNotEmpty && !stopWords.contains(word))
          .toList();
    }
    
  • 多匹配择优:如果多个模型满足条件,返回关键词数量最多的结果,提升匹配精度:

    String? findBestMatchingResponse(List<String> userWords) {
      final userWordSet = Set<String>.from(userWords);
      vaModel? bestMatch;
      
      for (final model in vaData) {
        bool allMatch = model.stringData.every((keyword) => userWordSet.contains(keyword));
        if (allMatch) {
          if (bestMatch == null || model.stringData.length > bestMatch.stringData.length) {
            bestMatch = model;
          }
        }
      }
      
      return bestMatch?.response;
    }
    

内容的提问来源于stack exchange,提问作者emsiloader

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.09 11:20:30