我有两个字符串,里面有很多单词。
我的任务是找出两个字符串之间的单词匹配百分比。有人可以向我推荐我们已经拥有的算法来获得精确的百分比/匹配词。
示例:
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/