如何制作自动文字建议系统?

时间:2014-04-04 05:33:16

标签: lua lua-table

如果用户输入了无效命令,则它会将最接近的字符串返回给用户的输入。

source = {"foo", "foo1"}
Suggest = function (input, source)
--do stuff
end

因此,当用户输入未定义的命令“fo”时,例如它返回“foo”。 对不起,如果说得很清楚,那就匆忙了。

1 个答案:

答案 0 :(得分:4)

您可以使用LevenshteinDamerau–Levenshtein距离函数查找最接近输入的命令。 Here是一个实现这两个功能的C库。 Here是在Lua实施的Levenshtein距离。

以下函数假定distance是选择的距离函数。它使用可选的radius参数来指定从输入到建议的最大距离(如果用户输入的内容非常奇怪,您可能不希望提供任何建议,远离任何现有命令)。它返回一系列建议。

function suggest(input, source, radius)
   local result = {}
   local min_distance = radius or math.huge

   for _, command in ipairs(source) do
      local current_distance = distance(input, command)

      if current_distance < min_distance then
         min_distance = current_distance
         result = {command}
      elseif current_distance == min_distance then
         table.insert(result, command)
      end
   end

   return result
end

请注意,此搜索算法效率很低。根据命令数量和搜索速率,它可能会或可能不是您的问题。