如何比较两个句子并检索一个单词或几个单词,如果2个句子等于Java



我在变量字符串句中有一个输入句子,并希望与Java中的一组string []句子进行比较

String sentence = "I am fine today";
String[] sentence2= {"how are %s to day", I am %s today","thank %s for you answer"}

这个问题的输出导致真实条件(匹配(并检索一个单词" fine"。如果输入像这样更改:字符串sen =我今天很高兴,输出会导致真实条件(匹配(并检索单词" fine"

我有一个函数,并使用拆分将句子拆分为单词并与数组单词进行比较

 if (similarity(sentence,sentence2)>2) {
     String a = getkata(sentence, sentence2);
    ..
    }
    public static int similarity(String a, String b) {
            int count = 0;
            String[] words = a.split(" ");
           // String[] words2=b.split(" ");
            for (int i=0; i < words.length; i++){
                if(b.contains(words[i])) {
                    System.out.println(i);
                    count=count+1;
                }
            }
            return count;
        }
public static String getkata(String a, String b){
        String hasil="";
        String[] kata = a.split(" ");
        String[] cari = b.split(" ");
        for (int i=0; i< kata.length; i++){
            if(cari[i].contains("%s")){
                hasil = kata[i];
            }
        }
        return hasil;
}

此代码有效,但是我希望代码直接比较两个句子而不分为单词

如果您可以用(.*?)替换%s,则可以解决90%的问题,可以使用匹配项来检查:

public static void main(String[] args) {
    String sen = "I am fine today";
    String[] sen2 = {"how are (.*?) to day", "I am (.*?) today", "thank (.*?) for your answer"};
    for (String s : sen2) {
        if (sen.matches(s)) {
            System.out.print("Matche : ");
            System.out.println(sen);
        }else{
            System.out.println("Not Matche");
        }
    }
}

这将向您展示:

Not Matche
Matche : I am fine today
Not Matche

编辑

我想要一个布尔的答案,并检索%s Word

在这种情况下,您使用模式并匹配:

public static void main(String[] args) {
    String sen = "I am fine today";
    String[] sen2 = {"how are (.*?) to day", "I am (.*?) today", "thank (.*?) for your answer"};
    Pattern pattern;
    Matcher matcher;
    for (String s : sen2) {
        pattern = Pattern.compile(s);
        matcher = pattern.matcher(sen);
        if (matcher.find()) {
            System.out.println("Yes found : " + matcher.group(1));
        }
    }
}

输出

Yes found : fine

这应该有效:

    for (String s: sen2) {
        Pattern pat = Pattern.compile(s.replace("%s", "(.*)"));
        Matcher matcher = pat.matcher(sen);
        if (matcher.matches()) {
            System.out.println(matcher.group(1));
        }
    }

最新更新