我有一个程序可以将英语翻译成一种虚构的语言,比如 Sprite 语。
我的第一个想法是使用 HashMap 但当然,我做不到,
map.get("Hello, I am human");
让它检查“Hello”、“i”、“am”、“a”、“人类”,然后将其翻译为“Hallo, ich bin ein Mensch”或“龙,机器人猫鲸马”
我该怎么做?
最佳答案
我知道这可能不完全是你想要的,但这就是我的处理方法。可能有更好的方法来做到这一点(我正在考虑正则表达式或其他方法),但我不知道如何做到这一点,所以这是我拥有的最好的方法。
- 收集输入句子
- 拆分单词
- 如果该单词位于转换映射中:
检索转换后的单词并添加到数组
ArrayList<String> strings = new ArrayList<>(Arrays.asList("hello world", "this is a test")); HashMap<String, String> map = new HashMap<>(); map.put("hello", "wordForHello"); map.put("world", "wordForWorld"); map.put("this", "wordForThis"); map.put("is", "wordForIs"); map.put("a", "wordForA"); map.put("test", "wordForTest"); ArrayList<String> sentence = new ArrayList<>(); for (String str : strings) { String[] words = str.split(" "); for (String word : words) { if (map.containsKey(word)) { sentence.add(map.get(word)); } } System.out.println(sentence); sentence = new ArrayList<>(); }
关于java - 如何将句子输入到HashMap中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59400378/