zoukankan      html  css  js  c++  java
  • 将汉字转成拼音

    转成拼音工具类:

    package utils;
    
    import net.sourceforge.pinyin4j.PinyinHelper;
    
    public class PinyinUtils {
        /**
         * 提取每个汉字的首字母
         * 
         * @param str
         * @return String
         */
        public static String getPinYinHeadChar(String str) {
            String convert = "";
            for (int j = 0; j < str.length(); j++) {
                char word = str.charAt(j);
                // 提取汉字的首字母
    
                String[] pinyinArray = PinyinHelper.toHanyuPinyinStringArray(word);
                if (pinyinArray != null) {
                    convert += pinyinArray[0].charAt(0);
                } else {
                    convert += word;
                }
            }
            return convert;
        }
    
        /**
         * 获取汉字完整拼音
         * 
         * @param str
         * @return
         */
        public static String getPinYin(String str) {
            String value = "";
            for (int j = 0; j < str.length(); j++) {
                char word = str.charAt(j);
                String[] pinyinArray = PinyinHelper.toHanyuPinyinStringArray(word);
                if (pinyinArray != null) {
                    value += pinyinArray[0].substring(0,
                            pinyinArray[0].length() - 1);
                }
            }
            return value;
        }
    }

    测试类:

    package szoa;
    
    import java.io.BufferedReader;
    import java.io.BufferedWriter;
    import java.io.File;
    import java.io.FileInputStream;
    import java.io.FileOutputStream;
    import java.io.FileWriter;
    import java.io.IOException;
    import java.io.InputStreamReader;
    import java.io.OutputStreamWriter;
    
    public class testPinyin {
        
    
        public static void main(String[] args) throws IOException {
            
            String filename = "C:\Users\sjx\Desktop\a.txt";
            BufferedReader br = new BufferedReader(new InputStreamReader(new FileInputStream(filename), "utf-8")); //这里可以控制编码
            String line = null;
            BufferedWriter  out = new BufferedWriter(new OutputStreamWriter(new FileOutputStream("C:\Users\sjx\Desktop\b.txt",true)));
            while ((line = br.readLine()) != null) {
             line = PinyinUtils.getPinYin(line);
              out.write(line + "
    ");
            }
            out.close();
        }
    }
  • 相关阅读:
    Java多线程(二)关于多线程的CPU密集型和IO密集型这件事
    Java 过一下基础
    日历打印用java实现
    DAY8-打卡第八天-2018-1-18
    web-day1-初识标识符
    DAY7-图形界面第一弹-2018-1-17
    四种排序方法用java实现
    DAY6-小变化(java提示框)-2018-1-16
    DAY5-小别-2018-1-15
    DAY4-打卡第四天-2018-1-12
  • 原文地址:https://www.cnblogs.com/sjxbg/p/10440151.html
Copyright © 2011-2022 走看看