2013-12-20 61 views
0

我非常不確定如何執行此操作。我明白了(我相信),您使用從數組中獲取單詞

String[] user {"stuff","other stuff","more stuff"}; 

我開發一個聊天機器人,我需要它能夠識別用戶所說的話,如果它是每個數組(它的「數據庫」,裏面說),那麼它會作出相應的迴應。

一些簡單的東西,我可以說,「你好嗎?」它會尋找「你好嗎?」或者至少接近它並用隨機的正面詞語做出相應的迴應。我通過簡單地使用很多if-else語句來實現這個功能,但這是太多的編碼。

+0

我認爲你在這裏尋找的是自然語言處理,並不能真正在堆棧溢出的線程中解釋。我冒昧地猜測你可以用簡單的正則表達式來得到簡單的東西。這又是一個很大的話題。嘗試使用谷歌搜索「在java中的正則表達式」開始 –

回答

1

如果我正確理解你,你希望你的機器人響應來自用戶的一些提示。在這種情況下,您可以使用Map<String, String>來存儲查詢 - 答案對。

Map<String, String> answers = new HashMap<String, String>(); 

answers.put("How are you?", "Great!"); 
answers.put("Where is the cake?", "The cake is a lie"); 

,然後只檢查查詢字符串是否是答案:

public String answerUser(String query) { 
    if (answers.containsKey(query)) { 
     return answers.get(query); 
    } else { 
     return "I don't understand."; 
    } 
} 

如果你想不止一個可能的答案,使用Map<String, List<String>>然後從列表中隨機選擇:

public String answerUser(String query) { 
    Random rand = new Random(); 

    if (answers.containsKey(query)) { 
     List<String> ans = answers.get(query); 
     int id = rand.nextInt(ans.size()); 
     return ans.get(id); 
    } else { 
     return "I don't understand."; 
    } 
} 
0

這是一個非常大而複雜的主題,你還沒有真正發佈足夠的信息。

要將字符串拆分爲單詞使用String#split(),那會給你你想要的數組。 (你可能想分割所有非alpha或全部空白)。

然後,您需要定義AI響應的關鍵字,並掃描陣列中的任意關鍵字。

使用某種評分系統,然後確定適當的響應。

例如,您可以將String的HashMap應用於具有權重和含義的類。通過句子,總結你發現的每一個動作的分數。根據綜合值做出適當的決定。

這是一個非常簡單的算法,更好的算法是可能的,但它們更難,這會讓你開始。

+0

謝謝,所有這些。加權回答似乎是一個非常好的主意,我已經有了一種類似於此的想法(儘管我無法正確理解它,所以非常感謝)添加模擬情緒,將用戶輸入權衡到決定AI如何「感受」的設置是什麼。 –

0

您可以使用列表而不是數組,它會給你contains()方法。例如:

List<String> words = new ArrayList<String>(); 
words.add("Hello"); 
words.add("bye"); 
if(words.contains("hello")) { 
    //do something 
} 

另一種選擇是將短語映射到響應:如果你想

Map<String, String> wordMap = new HashMap<String, String>(); 
wordMap.put("How are you?", "Great"); 
wordMap.put("Where are you?", "Work"); 
wordMap.get("How are you?"); 

結合這些並映射一個短語來響應清單。

0

一個智能聊天機器人需要更多的設計,但如果你只是想要一個解決方案,其中「我說這個,那麼你說,」比你可以做幾種方法。

使用兩個數組

既然你知道如何使用一個數組,想我會從這裏開始的簡單性。

String[] userInput {"how are you", "how are you?", "how you doing?"}; 
String[] response {"good", "terrible", "is that a joke?"}; 

//Go through each userInput string and see if it matches what you typed in. 
    //If it matches, print the corresponding position in the response array. 

使用地圖

同樣的想法,但它是一個集合,是更適合的情況。

Map<String, String> response = new HashMap<String, String>(); 
response.add("how are you", "good"); 

//When you receive input, check the response map using the input as the key. 
//Return the value as the response. 
//Better documented in sebii's answer.