zoukankan      html  css  js  c++  java
  • Java中汉字转拼音

    需要下载pinyin4j:http://pinyin4j.sourceforge.net/

    代码
    package utils;

    import net.sourceforge.pinyin4j.*;
    import net.sourceforge.pinyin4j.format.*;
    import net.sourceforge.pinyin4j.format.exception.*;

    public class PinYin {
        
    /**
         * 将汉字转换为全拼
         * 
         * 
    @param src
         * 
    @return
         
    */
        
    public static String getPingYin(String src) {
            
    char[] t1 = null;
            t1 
    = src.toCharArray();
            String[] t2 
    = new String[t1.length];
            HanyuPinyinOutputFormat t3 
    = new HanyuPinyinOutputFormat();
            t3.setCaseType(HanyuPinyinCaseType.LOWERCASE);
            t3.setToneType(HanyuPinyinToneType.WITHOUT_TONE);
            t3.setVCharType(HanyuPinyinVCharType.WITH_V);
            String t4 
    = "";
            
    int t0 = t1.length;
            
    try {
                
    for (int i = 0; i < t0; i++) {
                    
    // 判断是否为汉字字符
                    if (java.lang.Character.toString(t1[i]).matches(
                            
    "[\\u4E00-\\u9FA5]+")) {
                        t2 
    = PinyinHelper.toHanyuPinyinStringArray(t1[i], t3);
                        t4 
    += t2[0];
                    } 
    else
                        t4 
    += java.lang.Character.toString(t1[i]);
                }
                
    // System.out.println(t4);
                return t4;
            } 
    catch (BadHanyuPinyinOutputFormatCombination e1) {
                e1.printStackTrace();
            }
            
    return t4;
        }

        
    /**
         * 返回中文的首字母
         * 
         * 
    @param str
         * 
    @return
         
    */
        
    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;
        }

        
    public static void main(String[] args) {
            String cnStr 
    = "中华人民共和国";
            System.out.println(getPingYin(cnStr));
            System.out.println(getPinYinHeadChar(cnStr));
        }
    }
  • 相关阅读:
    Python Cookbook(第3版)中文版:15.20 处理C语言中的可迭代对象
    Python Cookbook(第3版)中文版:15.21 诊断分段错误
    Theano环境搭建/安装
    Keras官方中文文档:keras后端Backend
    Keras官方中文文档:函数式模型API
    Keras官方中文文档:序贯模型API
    Keras官方中文文档:关于Keras模型
    Keras官方中文文档:序贯模型
    web服务器原理
    静态网页与动态网页区别
  • 原文地址:https://www.cnblogs.com/yvesliao/p/1773040.html
Copyright © 2011-2022 走看看