问题
I googled these days but nothing helps. I m not sure now if its possible, so I thought I just aks at stackoverflow.
The situation: The user can input a word or in a inputbox. When he finishes a function check if the word is in the array of words - easy. Now I wanna write a help, if one letter is missing or the letters are written the wrong way, a message should popout.
What are the keys to search for? I tried:
- javascript find string in array
- javascript find similar words in array
- javascript regex similar words
- ... and more
I hope you undestand what i mean, and can give me some hints.
回答1:
The Levenshtein distance is a metric for computing the distance between similar words. For each changed, shuffled or missing letter the distance is increased. You can read more here: http://en.wikipedia.org/wiki/Levenshtein_distance
and take a reference for the implementation in different languages here: http://en.wikibooks.org/wiki/Algorithm_Implementation/Strings/Levenshtein_distance
I hope that helps and thanks for the comment up votes ;)
回答2:
See here for an algorithm to check for similarity between words.
Using the code from there, you can use array.any?{|e| e.similar?(user_input)}
You may adjust the threshold as required. Of course, this is Ruby, so you'd have to translate to javascript...
I copied the code from there:
class String
def levenstein(other, ins=2, del=1, sub=1)
return nil if self.nil? || other.nil?
dm = []
dm[0] = (0..self.length).collect { |i| i * ins}
fill = [0] * (self.length - 1)
for i in 1..other.length
dm[i] = [i * del, fill.flatten]
end
for i in 1..other.length
for j in 1..self.length
dm[i][j] = [
dm[i-1][j-1] + (self[i-1] == other[i-1] ? 0 : sub),
dm[i][j-1] + ins,
dm[i-1][j] + del
].min
end
end
dm[other.length][self.length]
end
def similar?(other, thresh = 2)
self.levenstein(other) < thresh
end
end
# Tryout
"Foobar".similar?("Fuubar", 3) # => true
来源:https://stackoverflow.com/questions/11377096/find-similar-words-in-array-of-words