我有一堆短语的列表。由于这是一个相当长的列表,我还有一个文本框,用户可以将其作为搜索栏输入。截至目前,搜索栏中的字母不完全包含的条款将被滤除。然而,我想让它列出一些关于这个词可能是什么的建议。执行模糊搜索建议/单词完成
注:我不是在寻找像那些here或here或here(虽然this image从第一环节似乎不错)一个“你的意思是......”或拼写检查算法;我想要一个算法,能够建议不完整的单词或短语的最佳匹配;例如单词"bat"
应该是单词"battery"
比单词"car"
更好的匹配。
使用Google返回以(大致)相同的字母开头的最常见的字符串的方法也是不切实际的,因为据我所知,列表中的每个元素都是相同的和其他人一样。我想在Java(8)中做到这一点;然而,其他语言答案是可以接受的,只要他们不使用Java没有的同等功能的内置函数。如果它有用,我写了一个Levenshtein距离的修改版本(见下文),它填充搜索字符串时用星号表示“任何字符”。这适用于单个单词,例如"mud"
与完美匹配,但在考虑人们可能使用"car"
来搜索"race car"
时不够好。
/**
* <ul>
* <b><i>searchDistance</i></b><br>
* <br>
* <code> public static int searchDistance(String key, String match)</code><br>
* <br>
* Gets the Levenshtein distance between <code>key</code> and <code>match</code>. <br>
* If <code>useAsterisk</code> is true, then the follwing applies: If <code>key</code> is shorter than <code>match</code>, the asterisk <code>'*'</code> is appended to it until the lengths are equal. Asterisks can be used in <code>key</code> to signify 'any character.'
* @param key - The text to search for
* @param match - The text to compare <code>key</code> against
* @param useAsterisk - Whether or not to use asterisks for the purpose described above
* @return the Levenshtein distance between <code>key</code> and <code>match</code>.
* </ul>
*/
public static int searchDistance(String key, String match, boolean useAsterisk) {
while (key.length() < match.length()) {
key = key + "*";
}
int[][] matrix = new int[key.length() + 1][match.length() + 1];
for (int i = 0; i < matrix.length; i++) {
matrix[i][0] = i;
}
for (int i = 0; i < matrix[0].length; i++) {
matrix[0][i] = i;
}
for (int a = 1; a < matrix.length; a++) {
for (int b = 1; b < matrix[0].length; b++) {
matrix[a][b] = Math.min(Math.min(matrix[a - 1][b] + 1, matrix[a][b - 1] + 1), matrix[a - 1][b - 1] + (key.charAt(a - 1) == match.charAt(b - 1) || key.charAt(a - 1) == '*' ? 0 : 1));
}
}
return matrix[matrix.length - 1][matrix[0].length - 1];
}
TL; DR:是否有一种很好的方式可以为搜索字词提供完成建议?
在此先感谢!
看起来不错,尝试一下;然而,它仍然是一种比较的方法,而不是完成的,也是对文件,mot小句子。仍然可能是好的;谢谢。 – ricky3350