【问题标题】:String Approximation (Fetching the nearest matched String from Dictionary)字符串逼近(从字典中获取最近的匹配字符串)
【发布时间】:2012-09-03 08:59:48
【问题描述】:

是否有任何字符串匹配代码或算法可以为我们提供字典中近似匹配的字符串(包含预定义的字符串集)?

例如:如果字典中有 10 个字符串(Set of Strings),如果用户输入了一些字符串,那么算法应该告诉您字典中的近似匹配字符串。如果我得到具有匹配值(或百分比)的匹配字符串,那就太好了。

【问题讨论】:

  • 欢迎来到 SO。查找字典有多大?

标签: java string string-matching approximation


【解决方案1】:

我认为最好使用 lucene 库,它有一个名为 org.apache.lucene.search.spell 的包,您可以轻松使用它。它提供3种算法NGramDistance、LevensteinDistance、JaroWinklerDistancetry this

【讨论】:

    【解决方案2】:

    您可以在您的字符串和字典中的字符串之间计算Levenshtein distance,以找到最接近的匹配项。这可能不是拼写检查的最佳选择,因为它不利于交换字母或语音相似的单词。例如问题比 kwizchum 更接近于休息。

    更多示例,您可以阅读http://en.wikipedia.org/wiki/Approximate_string_matching

    【讨论】:

      【解决方案3】:

      我只是想补充一点,StringUtils 从 3.0 版开始也有 a convenient Levenshtein Distance method

      public static int getLevenshteinDistance(CharSequence s,
                           CharSequence t)
      

      之后,它就像遍历集合并记住最接近的匹配一样简单:

      public static Object findClosestMatch(Collection<?> collection, Object target) {
          int distance = Integer.MAX_VALUE;
          Object closest = null;
          for (Object compareObject : collection) {
              int currentDistance = StringUtils.getLevenshteinDistance(compareObject.toString(), target.toString());
              if(currentDistance < distance) {
                  distance = currentDistance;
                  closest = compareObject;
              }
          }
          return closest;
      }
      

      请注意,上面的方法确实需要集合是空安全的,并且 toString() 需要被合理地实现。

      【讨论】:

      • if 中没有“distance = currentDistance”吗?
      • 糟糕,我不得不删除一些特定的代码,看来我太急了:)
      【解决方案4】:

      你可以试试Levenshtein Distancetechinque。

      简单的想法你有四个基本操作:

      • 插入(地狱 -> 地狱 o
      • 替换(不错 -> r 冰)
      • 删除(bowlin g -> Bowlin)
      • 交换(兄弟 -> 兄弟 th er)

      您的算法应该计算您的单词与字典中每个单词之间的距离。最小的距离意味着这个词与给定的输入匹配得更准确。

      【讨论】:

        猜你喜欢
        • 2011-08-17
        • 2017-03-29
        • 2011-05-11
        • 2016-08-06
        • 1970-01-01
        • 2013-07-10
        • 1970-01-01
        • 1970-01-01
        • 2017-07-13
        相关资源
        最近更新 更多