比较两个句子并检查它们是否有相似的单词



我试着取两个句子,看看它们是否有共同的单词。示例:
A-";你好,世界这是一个测试">
B-";创造事物的测试;

这里的常用词是";测试";

我尝试使用.contains(),但它不起作用,因为我只能搜索一个单词。

text1.toLowerCase ().contains(sentence1.toLowerCase ())

在空白处拆分后,可以从这两个单词创建HashSets。您可以使用Set#retainAll来查找交集(常用词(。

final String a = "Hello world this is a test", b = "Test to create things";
final Set<String> words = new HashSet<>(Arrays.asList(a.toLowerCase().split("\s+")));
final Set<String> words2 = new HashSet<>(Arrays.asList(b.toLowerCase().split("\s+")));
words.retainAll(words2);
System.out.println(words); //[test]

在两个句子之间加空格,并将集合中第一个字符串中的每个单词相加。现在,在循环中,尝试添加集合中第二个字符串中的单词。如果加法运算返回false,则它是一个常用词。

import java.util.Arrays;
import java.util.HashSet;
import java.util.Set;
public class Sample {
public static void main(String[] args) {
// TODO Auto-generated method stub
String str1 = "Hello world this is a test";
String str2 = "Test to create things";
str1 = str1.toLowerCase();
str2 = str2.toLowerCase();
String[] str1words = str1.split(" ");
String[] str2words = str2.split(" ");
boolean flag = true;
Set<String> set = new HashSet<String>(Arrays.asList(str1words));
for(int i = 0;i<str2words.length;i++) {
flag = set.add(str2words[i]);
if(flag == false)
System.out.println(str2words[i]+" is common word");
}
}
}

您可以按空格分隔句子,将单词收集为列表,然后在另一个列表中搜索一个列表项,并收集常用单词。

这里是一个使用JavaStream API的示例。这里,第一句话的单词收集为Set,以加快每个单词的搜索操作(O(1)(

String a = "Hello world this is a test";
String b = "Test to create things";
Set<String> aWords = Arrays.stream(a.toLowerCase().split(" "))
.collect(Collectors.toSet());
List<String> commonWords = Arrays.stream(b.toLowerCase().split(" "))
.filter(bw -> aWords.contains(bw))
.collect(Collectors.toList());
System.out.println(commonWords);

输出:test

这里有一种方法:

// extract the words from the sentences by splitting on white space
String[] sentence1Words = sentence1.toLowerCase().split("\s+");
String[] sentence2Words = sentence2.toLowerCase().split("\s+");

// make sets from the two word arrays
Set<String> sentence1WordSet = new HashSet<String>(Arrays.asList(sentence1Words));
Set<String> sentence2WordSet = new HashSet<String>(Arrays.asList(sentence2Words));

// get the intersection of the two word sets
Set<String> commonWords = new HashSet<String>(sentence1WordSet); 
commonWords.retainAll(sentence2WordSet);        

这将产生一个包含两个句子之间常用单词的小写版本的集合。如果它是空的,就没有相似之处。如果你不在乎介词之类的单词,你可以把它们从最终的相似性集中过滤出来,或者更好的是,先对句子进行预处理,去掉这些单词。

请注意,现实世界中(即有用的(相似性检查的实现通常要复杂得多,因为您通常想要检查相似但有微小差异的单词。对于这些类型的字符串相似性检查,一些有用的起点是Levenstein距离和变音。

注意,上面的代码中有一个集合的冗余副本,我在那里创建了commonWords集合,因为交集是在适当的位置执行的,所以你可以通过简单地在句子1WordSet上执行交集来提高性能,但我更喜欢代码的清晰度而不是性能

试试这个。

static boolean contains(String text1, String text2) {
String text1LowerCase = text1.toLowerCase();
return Arrays.stream(text2.toLowerCase().split("\s+"))
.anyMatch(word -> text1LowerCase.contains(word));
}

String text1 = "Hello world this is a test";
String text2 = "Test to create things";
System.out.println(contains(text1, text2));

输出:

true

最新更新