java - 两个文本文件之间的单词匹配百分比算法

标签 java algorithm

我有两个字符串,里面有很多单词。

我的任务是找出两个字符串之间的单词匹配百分比。有人可以向我推荐我们已经拥有的算法来获得精确的百分比/匹配词。

示例:

1. Mason natural fish oil 1000 mg omega-3 softgels - 200 ea
2. Mason Vitamins Omega 3 Fish Oil, 1000mg. Softgels, Bonus Size 200-Count Bottle

**Output** should be 8 words matched between two strings.

最佳答案

您可以使用下面的方法。我添加了内联注释来描述您可以尝试的每个步骤。请注意,在此代码示例中,我使用了空格字符来拆分单词。如果您有任何疑虑,可以添加评论。

请注意,我在匹配单词时忽略了大小写,否则在您给出的示例中不可能有 8 个匹配单词。

public static int matchStrings(String firstString, String SecondString) {

    int matchingCount = 0;

    //Getting the whole set of words in to array. 
    String[] allWords = firstString.split("\\s");
    Set<String> firstInputset = new HashSet<String>();

    //getting unique words in to set
    for (String string : allWords) {
        firstInputset.add(string);
    }

    //Loop through the set and check whether number of words occurrence in second String
    for (String string : firstInputset) {
        if (SecondString.toLowerCase().contains(string.toLowerCase())) {
            matchingCount++;
        }
    }
    return matchingCount;
}

关于java - 两个文本文件之间的单词匹配百分比算法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41012120/

相关文章:

algorithm - 具有下一个和上一个支持的随机数生成?

javascript - 如何使用 Ember.run.later 实现秒表倒计时

java - 网络请求后未释放的对象

Java 泛型通配符扩展最终类

java正则表达式将数字与字符串分开

Ruby 在一行中打印两个整数而不使用字符串插值

c++ - partial_sort 与 nth_element 的复杂性

r - 通过算法检测时间序列中的跳跃

java - 实现接口(interface)时避免使用无体抽象方法 - java

java - 尝试运行客户端时出现 EJB 异常