及其原始代码,以防今后有类似场景需要使用,特意记录一下;
功能为计算拼音声母出现次数及概率
public static void main(String[] args) { //测试文本 String testStr = "wo\tyu\tfu\tqin\tbu\txiang\tjian\tyi\ter\tnian"; String[] testAtrArr = testStr.split("\t"); //声母表 String[] soundArr = new String[]{"b","p","m","f","d","t","n","l","g","k","h","j","q","x","zh","ch","sh","r","z","c","s","y","w"}; //声母出现次数 Map soundTimesMap = new TreeMap<String, Integer>(); //测试文字长度 int testWordLenth = testAtrArr.length; for (int i = 0; i < testWordLenth; i++) { String testFirstStrTemp = testAtrArr[i].substring(0,1); String testSecondStrTemp = testAtrArr[i].substring(0,2); for (int j = 0; j < soundArr.length; j++) { String soundArrTemp = soundArr[j]; if (testFirstStrTemp.equals(soundArrTemp) && testSecondStrTemp != "zh" && testSecondStrTemp != "ch" && testSecondStrTemp != "sh") { int count = 1; if (soundTimesMap.containsKey(soundArrTemp)) { count = (int) soundTimesMap.get(soundArrTemp) + 1; } soundTimesMap.put(soundArrTemp, count); break; } if (testSecondStrTemp.equals(soundArrTemp)) { int count = 1; if (soundTimesMap.containsKey(soundArrTemp)) { count = (int) soundTimesMap.get(soundArrTemp) + 1; } soundTimesMap.put(soundArrTemp, count); break; } } } System.out.println(soundTimesMap); Set<Map.Entry> entrySet = soundTimesMap.entrySet(); NumberFormat numberFormat = NumberFormat.getInstance(); // 设置精确到小数点后2位 numberFormat.setMaximumFractionDigits(2); Map soundRateMap = new TreeMap(); for (Map.Entry entry : entrySet) { soundRateMap.put(entry.getKey(), numberFormat.format(Float.valueOf(((Integer) entry.getValue()).toString()) * 100 / (float) testWordLenth)); } System.out.println(soundRateMap); }