0

我有一个 HashMap,其中某些键(例如“崩溃”和“崩溃”)返回相同的响应。我想创建一个新的 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();
}
4

2 回答 2

1

在有点混乱之后,我写了一个函数来查找同义词,然后返回默认消息。

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

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

于 2013-02-26T08:05:29.180 回答
0

您可以使用第二张地图。

第一个映射将同义词翻译成基本键,然后可以将其用于带有答案的第二个映射。

这也允许在不扩大实际响应图的情况下灵活扩展同义词。

此外,在这种情况下,您实际上可以使用另一种类型作为答案映射的键。它只需要与同义词映射的值类型相同。

这样,你也可以使用

Map<String, YourEnum> and Map<YourEnum, String> 

使用 EnumMap 作为 Map 接口的实现。

于 2013-02-26T07:50:53.530 回答