我有一个HashMap,其中某些键(例如“ crash”和“ crashes”)会返回相同的响应。我想创建一个新的HashMap,将同义词映射到responseMap中的唯一键(例如,在synonymMap中将“ crash”,“ crashes”和“ crashed”映射到“ crash”)。

 private void fillSynonymMap()
  {
    synonymMap.put("crash", "crash");
    synonymMap.put("crashes", "crash");
    synonymMap.put("crashed", "crash");
  }


我所坚持的是如何输入这些键,以便简化下面的代码。

 private void fillResponseMap()
{
    responseMap.put("crash",
                    "Well, it never crashes on our system. It must have something\n" +
                    "to do with your system. Tell me more about your configuration.");
    responseMap.put("crashes",
                    "Well, it never crashes on our system. It must have something\n" +
                    "to do with your system. Tell me more about your configuration.");\
   responseMap.put("crashed",
                    "Well, it never crashes on our system. It must have something\n" +
                    "to do with your system. Tell me more about your configuration.");
}



public String generateResponse(HashSet<String> words)
{
    for (String word : words) {
        String response = responseMap.get(word);
        if(response != null) {
            return response;
        }
    }

    // If we get here, none of the words from the input line was recognized.
    // In this case we pick one of our default responses (what we say when
    // we cannot think of anything else to say...)
    return pickDefaultResponse();
}

最佳答案

经过一番混乱之后,我编写了一个函数,该函数将查找同义词,然后返回默认消息。

public String getResponse()
{
    HashMap<String, String> responseMap = new HashMap<String, String>();
    HashMap<String, String> synonymMap = new HashMap<String, String>();

    responseMap.put("crash", "Hello there");
    // Load the response value.
    synonymMap.put("crash", "crash");
    synonymMap.put("crashed", "crash");
    synonymMap.put("crashes", "crash");
    // Load the synonyms.

    String input = "crashed";
    // Select input value.

        if(responseMap.containsKey(input))
        {
            // Response is already mapped to the word.
            return responseMap.get(input);
        }
        else
        {
            // Look for a synonym of the word.
            String synonym = synonymMap.get(input);
            if(!synonym.equals(input) && responseMap.containsKey(synonym))
            {
                // If a new value has been found that is a key..
                return responseMap.get(synonym);
            }
        }
        // If no response, set default response.
    input = "This is a default response";
    return input;
}


如您所见,该函数首先检查密钥是否存在。如果没有,它将尝试一个同义词。如果该同义词未通过测试,它将移至底部的默认代码,该代码会将输入设置为某个默认值,然后返回该默认值:)

10-01 20:23