使用Java搜索结果预览

让我们说我有以下文字(从
wiki):

Java is a programming language
originally developed by James Gosling
at Sun Microsystems (which is now a
subsidiary of Oracle Corporation) and
released in 1995 as a core component
of Sun Microsystems’ Java platform.
The language derives much of its
syntax from C and C++ but has a
simpler object model and fewer
low-level facilities. Java
applications are typically compiled to
bytecode (class file) that can run on
any Java Virtual Machine (JVM)
regardless of computer architecture.
Java is a general-purpose, concurrent,
class-based …

我想将“java”和“编程”匹配解析为google样式结果,如下所示:

Java is a programming language
originally developed by James Gosling
at Sun Microsystems Java
applications are typically compiled to
bytecode (class file) that can run on
any Java Virtual Machine (JVM)

>我可以使用哪些工具以及如何使用它们来获得上述结果. Commons,Lucene,指南针?
>如果有算法会突出显示关键字并注意剪切字符串并在最后添加“…”,请分享.
>您如何确定在搜索结果预览中显示的关键字数量和关键字?

最佳答案 我不知道有任何工具可以帮助解决这个问题,但我可以提供一种算法,可以给你相当不错的结果. *编辑:OP要求索引的示例代码.我使用
Trove TIntObjectHashMap存储此信息,但您可以使用Java HashMap执行相同操作.

步骤1:搜索每个搜索词的文本,并在文本中创建每个搜索词的偏移索引.

TIntObjectHashMap<String> matchIndex = new TIntObjectHashMap<String>();
// for each word or other string to highlight
// find each instance of each word in the string
// this is pseudocode -v
for (each instance of String searchString appearing at index int x)
  matchIndex.put(x, searchString);

步骤2:在步骤1中浏览每对索引的组合,并记录索引和命中数之间的字符数.

// class to hold a match
private class Match implements Comparable {
  private int x1, x2;
  private int hitCount;

  public Match(int x1, int x2, int hitCount); // does the obvious

  private double sortValue() {
    return (double) hitCount / Math.abs(x1, x2);
  }  

  @Override
  public int compareTo(Match m) {
    double diff = this.sortValue() - m.sortValue();
    if (diff == 0.0) return 0;
    return (diff < 0.0) ? -1 : 1;
  }
}

// go through every combination of keys (string offsets) and record them
// the treeset will automatically sort the results
TreeSet<Match> matches = new TreeSet<Match>();
int[] keys = matchIndex.keys();
for (int x1 = 0; x1 < keys.length; x1++)
  for (int x2 = x1 + 1; x2 < keys.length; x2++)
    matches.put(new Match(keys[x1],
                          keys[x2] + matchIndex.get(keys[x2]).length(),
                          1 + x2 - x1));

步骤3:获取步骤2中生成的列表,并按每个字符长度的点击次数对其进行排序.

// nicely done by the TreeSet

步骤4:从步骤3中列表的顶部开始,并将每个项目标记为包含在内.务必将重叠结果组合成一个更大的结果.当下一个项目将字符串的总长度超过255(或者更多)字符时停止.

步骤5:按顺序显示步骤4中的每个选定项目,它们之间带有“…”.请务必在每个项目中包含必要的标记以突出显示实际搜索词本身.

点赞