在飞镖中对字符串列表中的项目进行排名

rank items in list of string in dart

让我们考虑一个列表:

List<String> recipeNamesList = [
  'Burger',
  'French Fries',
  'Pizza',
  'Bengali Lamb Curry',
  'Chingri Malai Curry',
]

如果用户搜索 Bengali Lamb Fries 我需要 return Bengali lamb curryFrench Fries.

Benagli Lamb Curry 将获得最高排名,因为它有 2 个词匹配,而 French Fries 只有一个词匹配。

所以 returned 列表将是这样的:

List<String> result = [
  'Bengali Lamb Curry',
  'French Fries'
]

我当前的代码:

  Future<List<String>> getSuggestions(String search) async {
    List<String> results = [];
    List<String> searchSplit =
        search.toLowerCase().split(" "); // split the search query

    for (int i = 0; i < searchSplit.length; i++) {
      // iterate over search query
      for (int j = 0; j < recipeNamesList.length; j++) {
        // iterate over the recipe names list
        List<String> recipeNamesListSplit =
            recipeNamesList[j].split(" "); // split the recipe names
        for (int k = 0; k < recipeNamesListSplit.length; k++) {
          // iterate over the list of splitted name
          if (recipeNamesListSplit[k]
              .toLowerCase()
              .startsWith(searchSplit[i])) {
            // convert to lower case and check if the query is present in splitted name
            results
                .add(recipeNamesList[j]); // if contains == true add to results
          }
        }
      }
    }

    // Avoid repeated values
    results = results.toSet().toList();
    return results;
  }

这是一个完全临时的,只有当查询词出现在 recipeNamesList 中时才会匹配。如果是,则将它们添加到 results 列表中。它不会对搜索查询中匹配词最多的菜谱进行排名。

我应该如何排名?我当前的代码是否可以修改?还是我需要完全更改我的代码?

您需要将方法修改为

Future<List<String>> getSuggestions(String search) async {
  List<String> result = [];
  recipeNamesList.forEach((word){
    
    int value = getMatching(search,word);
    if(value > 0){
      if(result.isNotEmpty){
        if(getMatching(search,result[0]) > value){
          //only insert the maximum matched value at starting. it is some type of sorting
          result.add(word);
        }else{
          result.insert(0,word);
        }
      }else{
        result.add(word);
      }
    }
  });
}

精确匹配词统计的基本函数

int getMatching(String input, String word){
   List<String> inn = input.split(' ');
   List<String> words = word.split(' ');
   int temp = 0;
   inn.forEach((inWord){
     if(words.contains(inWord)){
       temp++;
     }
   });
   
   return temp;
 }

输出与输入getSuggestions('Bengali Lamb Fries')