how do you make a string dictionary function in lua?

混江龙づ霸主 提交于 2019-12-13 18:48:28

问题


Is there a way if a string is close to a string in a table it will replace it with the one in the table?

Like a spellcheck function, that searches through a table and if the input is close to one in the table it will fix it , so the one in the table and the string is the same?


回答1:


You can use this code :) Reference code is from here : https://github.com/badarsh2/Algorithm-Implementations/blob/master/Levenshtein_distance/Lua/Yonaba/levenshtein.lua

local function min(a, b, c)
    return math.min(math.min(a, b), c)
end

local function matrix(row,col)
  local m = {}
  for i = 1,row do m[i] = {}
    for j = 1,col do m[i][j] = 0 end
  end
  return m
end

local function lev(strA,strB)
  local M = matrix(#strA+1,#strB+1)
  local i, j, cost
  local row, col = #M, #M[1]
  for i = 1, row do M[i][1] = i - 1 end
  for j = 1, col do M[1][j] = j - 1 end
  for i = 2, row do
    for j = 2, col do
      if (strA:sub(i - 1, i - 1) == strB:sub(j - 1, j - 1)) then cost = 0
      else cost = 1
      end
    M[i][j] = min(M[i-1][j] + 1,M[i][j - 1] + 1,M[i - 1][j - 1] + cost)
    end
  end
  return M[row][col]
end

local refTable = {"hell", "screen"}

local function getClosestWord(pInput, pTable, threesold)
  cDist = -1
  cWord = ""
  for key, val in pairs(pTable) do
    local levRes = lev(pInput, val)
    if levRes < cDist or cDist == -1 then
      cDist = levRes
      cWord = val
    end
  end
  print(cDist)
  if cDist <= threesold then
    return cWord
  else
    return pInput
  end
end

a = getClosestWord("hello", refTable, 3)
b = getClosestWord("screw", refTable, 3)
print(a, b)

Third parameter is threesold, if min distance is higher than threesold, word is not replaced.



来源:https://stackoverflow.com/questions/42681501/how-do-you-make-a-string-dictionary-function-in-lua

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!