2010-10-19 106 views
1

比方說,我有一本書的標題,我在數據庫中搜索它。數據庫產生匹配,其中一些是完全匹配的,其中一些是部分匹配的。如何檢查一個字符串中的每個單詞是否在另一個字符串中找到?

A full match是當搜索結果中的每個單詞由搜索項中的單詞表示時。(i.e. there does not have to be a complete overlap on both sides)

我只關心找到完整匹配。

所以,如果我爲"Ernest Hemingway - The Old Man and the Sea"鍵入搜索,並將結果返回如下:

Charles Nordhoff - Men Against The Sea 
Rodman Philbrick - The Young Man and the Sea 
Ernest Hemingway - The Old Man and the Sea 
Ernest Hemingway - The Sun Also Rises 
Ernest Hemingway - A Farewell to Arms 
Ernest Hemingway - For Whom the Bell Tolls 
Ernest Hemingway - A Moveable Feast 
Ernest Hemingway - True at First Light 
Men Against The Sea 
The Old Man and the Sea 
The Old Man and the Sea Dog 

在此列表中有兩個full matches:(根據上述定義)

Ernest Hemingway - The Old Man and the Sea 
The Old Man and the Sea 

在Java中這樣做,假設我有兩個變量:

String searchTerms; 
List<String> searchResults; 

在例如searchTerms上述代表着什麼我輸入:Ernest Hemingway - The Old Man and the Sea

searchResults代表字符串我從上面的數據庫返回的名單。

for (String result : searchResults) { 
    // How to check for a full match? 
    // (each word in `result` is found in `searchTerms` 
} 

我的問題是:在這個for-loop,我如何檢查在result字符串的每一個字是否有在searchTerms字符串對應詞?

回答

1

假設你的數據庫的結果是準確的,

分裂result成標記(字)使用String.split(String delimiter)並查看每個令牌是否在searchTerms發現(使用searchTerms.indexOf(String word) == -1)。

for (String result : searchResults) { 
    for(String word : result) { 
     if(searchTerms.indexOf(word) == -1) { 
      // result is not a full match 
     } 
    } 

    //If none of the if statements executed, statement is a full match. 
} 
3

要查找完全匹配,就像您定義它的那樣,您要測試一組標記是否包含特定的子集。您可以使用Set輕鬆完成此操作,您可以在收集庫中免費獲得這些信息。要做到這一點是(正則表達式的一邊爲代價)的一種方法:

Set<String> searchTerms = new HashSet<String>(); 
    Set<String> resultTokens = new HashSet<String>(); 

    searchTerms.addAll(Arrays.asList(searchString.split("\\s+")); 

    for (String result : searchResults) 
    { 
     resultTokens.clear(); 
     resultTokens.addAll(Arrays.asList(result.split("\\s+"))); 
     if (resultTokens.containsAll(searchTerms)) 
     { 
     // Perform match code 
     } 
    } 

另外,如果你想成爲它嚴格,你可以使用resultTokens.equals(searchTerms)測試集相等。在你的例子中,這將縮小結果集到「海明威 - 老人與海」

相關問題