我正在开发一个具有搜索功能的 Java 应用程序。现在,对于搜索,我正在使用通配符进行搜索。因此,如果有人搜索“Hello Kitty”,他们还会得到 kit、hell、hello 等结果。搜索后,我根据他们的点击为结果分配分数,但是我如何比较结果来得出结论:结果是100%匹配或80%匹配,例如“Hello Kit”,几乎与“hello kitty”匹配。有什么办法可以做到这一点吗?
搜索代码:
Directory directory = FSDirectory.open(path);
IndexReader indexReader = DirectoryReader.open(directory);
IndexSearcher indexSearcher = new IndexSearcher(indexReader);
Query query = new WildcardQuery(new Term("contents", "*" + str + "*"));
TopDocs topDocs = indexSearcher.search(query, 1000);
for (ScoreDoc scoreDoc : topDocs.scoreDocs) {
Document document = indexSearcher.doc(scoreDoc.doc);
IndexableField value = document.getField("score");
if (value != null) {
sortedMap.put(Integer.valueOf(document.get("id")), (Integer) value.numericValue());
} else {
sortedMap.put(Integer.valueOf(document.get("id")), 0);
}
}
indexSearcher.getIndexReader().close();
directory.close();
谢谢。
最佳答案
听起来您正在寻找骰子系数。这是一个java实现:
public static double diceCoefficient(String s1, String s2)
{
Set<String> nx = new HashSet<String>();
Set<String> ny = new HashSet<String>();
for (int i=0; i < s1.length()-1; i++) {
char x1 = s1.charAt(i);
char x2 = s1.charAt(i+1);
String tmp = "" + x1 + x2;
nx.add(tmp);
}
for (int j=0; j < s2.length()-1; j++) {
char y1 = s2.charAt(j);
char y2 = s2.charAt(j+1);
String tmp = "" + y1 + y2;
ny.add(tmp);
}
Set<String> intersection = new HashSet<String>(nx);
intersection.retainAll(ny);
double totcombigrams = intersection.size();
return (2*totcombigrams) / (nx.size()+ny.size());
}
https://en.wikibooks.org/wiki/Algorithm_Implementation/Strings/Dice%27s_coefficient#Java
该算法将 0 到 1 之间的数字分配给一对字符串,数字越大,它们越相似。所以基本上就是你所要求的。
关于Java:概率文本匹配,检测文本匹配的百分比。,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47054553/