我有一堆短語的列表。由於這是一個相當長的列表,我還有一個文本框,用戶可以將其作爲搜索欄輸入。截至目前,搜索欄中的字母不完全包含的條款將被濾除。然而,我想讓它列出一些關於這個詞可能是什麼的建議。執行模糊搜索建議/單詞完成
注:我不是在尋找像那些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