2017-04-27 67 views
-3

等於我在變量字符串句子的輸入句子,想用一組的String [] SENTENCE2像下面在Java中比較如何比較兩個句子,檢索詞或幾個單詞,如果2句子在java中

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

該問題的輸出結果爲真(匹配)並檢索到一個單詞「fine」。 如果輸入如下改變:String sen =今天我很高興,輸出結果爲真實條件(匹配)並檢索單詞「fine」

我有一個函數並使用split將句子拆分爲單詞並比較與陣列字

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; 
} 

此代碼的工作,但我想代碼直接比較兩個句子,而不分割成字

+3

甚至在我試圖重新格式化你的問題做出更易讀;我仍然不知道你想達到什麼。請提出一個真實的[mcve]並解釋你卡在哪裏;而不是僅僅提出要求。 – GhostCat

+0

你試圖實現你的目標的代碼是什麼? –

+0

第二個例子中的單詞應該是「開心」,我猜? – Henry

回答

1

如果你可以替換%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 

編輯

我想回答一個true和檢索%S字

在這你的情況使用模式和火柴例如:

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 
+0

它不是我想要的答案...我想要一個答案布爾值爲true並檢索%s字 – yudialcampari

+0

@yudialcampari檢查我的更新,可以在這種情況下使用模式 –

+0

謝謝你..你的回答解決了我的問題 – yudialcampari

0

這應該工作:

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)); 
     } 
    } 
+0

非常接近。我在發佈之前沒有看到更新。 –

+0

謝謝..解決 – yudialcampari

+1

我認爲matcher.matches()比matcher.find()更好... – yudialcampari