【问题标题】:Java language conversionJava语言转换
【发布时间】:2020-04-30 19:17:53
【问题描述】:

这是我用来将一些文本从猪拉丁语翻译成英语的代码,反之亦然。除了 fromPig 方法似乎无法正常工作。

预期输出:“java 是一门美妙的编程语言,而面向对象编程是切片面包之后最好的东西。”

得到输出:“avajavajay isyisyay ayay onderfulwonderfulway grammingprogrammingpray...”

所以你可以看到单词在里面,但我需要去掉单词末尾的其他部分。如果您能纠正我的错误,请尝试提供代码。

public class PigLatin {
    public String fromPig(String pigLatin) {
        String res="";
        String[] data=pigLatin.split(" ");
        for(String word : data)
        res += toEnglishWord(word) + " ";
        return res;
    }

    private String toEnglishWord(String word) {
        char punc=0;
        for(int i=0;i<word.length();i++) {
            if(word.charAt(i)=='.'||word.charAt(i)==','||word.charAt(i)==';'||word.charAt(i)=='!') {
                punc=word.charAt(i);
                break;
            }
        }
        word=word.replace(punc + "","");
        String[] data=word.split("-");
        String firstPart=data[0];
        String lastPart=data[0];
        if(lastPart.equals("yay"))
        return firstPart + punc ;
        else {
            lastPart=lastPart.replace("ay","");
            return(lastPart+firstPart+punc);
        }
    }
}

这是需要执行语句的类。

public class Convert {
    public static void main(String args []) {
        PigLatin demo=new PigLatin();
        String inEnglish="Now is the winter of our discontent " +
            "Made glorious summer by this sun of York; " +
            "And all the clouds that lour'd upon our house " +
            "In the deep bosom of the ocean buried.";
        String inPigLatin="avajay isyay ayay onderfulway ogrammingpray " +
            "anguagelay, andyay objectyay orientedyay ogrammingpray " +
            "isyay hetay estbay ingthay afteryay icedslay eadbray.";
        System.out.println(demo.toPig(inEnglish));
        System.out.println(demo.fromPig(inPigLatin));
    }
}      

基本上英文句子需要转成pig latin,pig latin句子需要转成英文。

英语到猪拉丁语正在正确完成。但是piglatin到英语不是。

【问题讨论】:

    标签: java


    【解决方案1】:

    解决以下问题:

    1. 将文本转换为单个大小写(例如小写),因为您只与小写元音进行比较。
    2. toEnglishWord 中的代码不正确。更改如下:
    private String toEnglishWord(String word) {
        char punc = 0;
        for (int i = 0; i < word.length(); i++) {
            if (word.charAt(i) == '.' || word.charAt(i) == ',' || word.charAt(i) == ';' || word.charAt(i) == '!') {
                punc = word.charAt(i);
                break;
            }
        }
        // Trim the word, and remove all punctuation chars
        word = word.trim().replaceAll("[\\.,;!]", "");
        String english = "";
    
        // If the word ends with 'yay', remove 'yay' from its end. Otherwise, if the
        // word ends with 'ay', form the word as (3rd last letter + characters from
        // beginning till the 4th last character). Also, add the punctuation at the end
        if (word.length() > 2 && word.substring(word.length() - 3).equals("yay")) {
            english = word.substring(0, word.length() - 3) + String.valueOf(punc);
        } else if (word.length() > 3 && word.substring(word.length() - 2).equals("ay")) {
            english = word.substring(word.length() - 3, word.length() - 2) + word.substring(0, word.length() - 3)
                    + String.valueOf(punc);
        }
        return english;
    }
    

    演示:

    class PigLatin {
        public String toPig(String english) {
            String res = "";
            String[] data = english.toLowerCase().split(" ");
            for (String word : data)
                res += toPigWord(word) + " ";
            return res;
        }
    
        public String fromPig(String pigLatin) {
            String res = "";
            String[] data = pigLatin.toLowerCase().split(" ");
            for (String word : data)
                res += toEnglishWord(word) + " ";
            return res;
        }
    
        private String toPigWord(String word) {
            char punc = 0;
            for (int i = 0; i < word.length(); i++) {
                if (word.charAt(i) == '.' || word.charAt(i) == ',' || word.charAt(i) == ';' || word.charAt(i) == '!') {
                    punc = word.charAt(i);
                    break;
                }
            }
            word = word.replace(punc + "", "");
            if (isFirstLetterVowel(word))
                return (word + "yay" + punc);
            else {
                int indexVowel = indexOfFirstVowel(word);
                String after = word.substring(indexVowel);
                String before = word.substring(0, indexVowel);
                return (after + before + "ay" + punc);
            }
        }
    
        private String toEnglishWord(String word) {
            char punc = 0;
            for (int i = 0; i < word.length(); i++) {
                if (word.charAt(i) == '.' || word.charAt(i) == ',' || word.charAt(i) == ';' || word.charAt(i) == '!') {
                    punc = word.charAt(i);
                    break;
                }
            }
            // Trim the word, and remove all punctuation chars
            word = word.trim().replaceAll("[\\.,;!]", "");
            String english = "";
    
            // If the word ends with 'yay', remove 'yay' from its end. Otherwise, if the
            // word ends with 'ay' and form the word as (3rd last letter + characters from
            // beginning to the 4th last character). Also, add the punctuation at the end
            if (word.length() > 2 && word.substring(word.length() - 3).equals("yay")) {
                english = word.substring(0, word.length() - 3) + String.valueOf(punc);
            } else if (word.length() > 3 && word.substring(word.length() - 2).equals("ay")) {
                english = word.substring(word.length() - 3, word.length() - 2) + word.substring(0, word.length() - 3)
                        + String.valueOf(punc);
            }
            return english;
        }
    
        private boolean isFirstLetterVowel(String word) {
            String temp = word.toLowerCase();
            return (temp.charAt(0) == 'a' || temp.charAt(0) == 'e' || temp.charAt(0) == 'i' || temp.charAt(0) == 'o'
                    || temp.charAt(0) == 'u');
        }
    
        private int indexOfFirstVowel(String word) {
            int index = 0;
            String temp = word.toLowerCase();
            for (int i = 0; i < temp.length(); i++) {
                if (temp.charAt(i) == 'a' || temp.charAt(i) == 'e' || temp.charAt(i) == 'i' || temp.charAt(i) == 'o'
                        || temp.charAt(i) == 'u') {
                    index = i;
                    break;
                }
            }
            return index;
        }
    }
    
    class Main {
        public static void main(String[] args) {
            PigLatin pigLatin = new PigLatin();
            String str = "hello world! good morning! honesty is a good policy.";
            String strToPigLatin = pigLatin.toPig(str);
            System.out.println(strToPigLatin);
            System.out.println(pigLatin.fromPig(strToPigLatin));
        }
    }
    

    输出:

    ellohay orldway! oodgay orningmay! onestyhay isyay ayay oodgay olicypay. 
    hello world! good morning! honesty is a good policy. 
    

    注意:按照目前的逻辑,没有办法将ogrammingpray(这是programming的piglatin)这样的单词转换回programming

    【讨论】:

    • 不过,我不认为你可以用“grammingpray”之类的东西做任何事情
    • 感谢您的反馈。你是绝对正确的。我已经在编辑我的答案来写这个注释。
    【解决方案2】:

    像这样将 Pig Latin 转换为英语是不可能的 - 你需要一个人,一个可以访问单词数据库的程序,或者一个神经网络或在单词数据库上训练过的东西。没有它,如果单词最初以元音开头,或者它们的第一个字母是辅音并且它们的第二个字母是元音,您只会将单词转换回英语。否则,机器实际上无法分辨单词最初的结束位置。

    因此,您需要创建一个输出List&lt;String&gt; 的方法,如下所示:

    public static List<String> allPossibleSentences(String inPigLatin) {
        List<String> pigWords = Arrays.asList(inPigLatin.split("\\s"));
        //You can also use a method reference here
        List<List<String>> possSentences = cartesianProduct(pigWords.stream().map(word -> possibleEnglishWords(word)).collect(Collectors.toList()));
        return possSentences.stream().map(words -> String.join(" ", words)).collect(Collectors.toList());
      }
    

    但是由于你的代码中需要一个 fromPig 方法,你可以这样写:

    public static String fromPig(String inPigLatin) {
      return allPossibleSentences(inPigLatin).get(0);
    }
    

    与 Arvind Kumar Avinash 的答案相比,这太强大了,因为它会生成所有排列,但我觉得如果你有最可能的情况 所有可能的句子,它会更有用。

    主要方法示例

    public static void main(String[] args) {
        String inPigLatin="avajay isyay ayay onderfulway ogrammingpray " +
                "anguagelay andyay objectyay orientedyay ogrammingpray " +
                "isyay hetay estbay ingthay afteryay icedslay eadbray";
        System.out.println(fromPig(inPigLatin));
        inPigLatin = "icedslay eadbray";
        System.out.println("\nExpected = sliced bread, gotten = " + fromPig(inPigLatin));
        System.out.println(String.join("\n", allPossibleSentences(inPigLatin)));
    }
    

    示例输出

    java is a wonderful rogrammingp language and object oriented rogrammingp is the best hingt after liceds readb
    
    Expected = sliced bread, gotten = liceds readb
    liceds readb
    liceds bread
    liceds dbrea
    sliced readb
    sliced bread //Here you have the right answer, but your method has no way to confirm that
    sliced dbrea
    dslice readb
    dslice bread
    dslice dbrea
    

    您现在的 PigLatin 课程

    import java.util.Arrays;
    import java.util.List;
    import java.util.ArrayList;
    import java.util.stream.Collectors;
    
    class PigLatin {
    
    //Put your toPig and toPigWord methods here (I couldn't find them)
    
    public static String fromPig(String inPigLatin) {
      return allPossibleSentences(inPigLatin).get(0);
    }
    
    /* Methods that above code relies on */
    private static List<String> possibleEnglishWords(String word) {
        List<String> possibilities = new ArrayList<>();
        if (word.matches(".*yay$")) {
          possibilities.add(word.substring(0, word.length() - 3));
          return possibilities;
        }
    
        //Remove the pig latin part
        word = word.substring(0, word.length() - 2);
        for (int i = word.length() - 1; i >= 0; i --) {
          if (isVowel(word.charAt(i))) break;
          if (word == "anguagel") System.out.println("char = " + word.charAt(i));
          possibilities.add(word.substring(i) + word.substring(0, i));
        }
        return possibilities;
      }
    
      //Put all the words together
      public static List<List<String>> cartesianProduct(List<List<String>> possWordArr) {
          if (possWordArr.size() == 1) {
            List<List<String>> possSentencesAsWords = new ArrayList<>();
            possSentencesAsWords.add(possWordArr.get(0));
            return possSentencesAsWords;
          }
          return _cartesianProduct(0, possWordArr);
      }
    
      //Helper method
      private static List<List<String>> _cartesianProduct(int index, List<List<String>> possWordArr) {
          List<List<String>> ret = new ArrayList<>();
          if (index == possWordArr.size()) {
              ret.add(new ArrayList<>());
          } else {
              for (String word : possWordArr.get(index)) {
                  for (List<String> words : _cartesianProduct(index + 1, possWordArr)) {
                      words.add(0, word);
                      ret.add(words);
                  }
              }
          }
          return ret;
      }
    
      private static boolean isVowel(char c) {
        c = toUppercase(c);
        switch (c) {
          case 'A':
          case 'E':
          case 'I':
          case 'O':
          case 'U':
            return true;
          default:
            return false;
        }
      }
    
      private static char toUppercase(char c) {
        if (c >= 'a') return (char) (((char) (c - 'a')) + 'A');
        else return c;
      }
    }
    

    【讨论】:

      猜你喜欢
      • 2012-10-06
      • 1970-01-01
      • 1970-01-01
      • 2023-04-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-06-20
      相关资源
      最近更新 更多