当前位置: 移动技术网 > IT编程>开发语言>Java > Java实现将汉字转化为汉语拼音的方法

Java实现将汉字转化为汉语拼音的方法

2019年07月22日  | 移动技术网IT编程  | 我要评论

本文实例讲述了java实现将汉字转化为汉语拼音的方法。分享给大家供大家参考,具体如下:

网上乱转,偶然看到一个很有意思的小工具,名字叫pinyin4j,可以把汉字转换为汉语拼音,利用他的话再配合上lucene、中文分词就可以做出类似google那种输入汉语拼音进行全文检索的功能了。实现的代码如下

package pinyin4j;
import net.sourceforge.pinyin4j.pinyinhelper;
import net.sourceforge.pinyin4j.format.hanyupinyincasetype;
import net.sourceforge.pinyin4j.format.hanyupinyinoutputformat;
import net.sourceforge.pinyin4j.format.hanyupinyintonetype;
import net.sourceforge.pinyin4j.format.hanyupinyinvchartype;
import net.sourceforge.pinyin4j.format.exception.badhanyupinyinoutputformatcombination;
public class pinyin4jtest {
  public static void main(string argsp[]) {
    try {
      string output = pinyin4jtest.cntopinyin("你和你好", null);
      system.out.println(output);
    } catch (badhanyupinyinoutputformatcombination e) {
      // todo auto-generated catch block
      e.printstacktrace();
    }
  }
  /**
   * @parm inputcn 输入的中文字符串
   * @parm seg 输出汉语拼音时的分隔符
   * 
   * hanyupinyinoutputformat提供了几种输出模式
   * hanyupinyincasetype:设定输入的结果是大写英文还是小写英文 lowercase :小写 uppercase :大写
   * hanyupinyintonetype:输出是否表明音调和重音 with_tone_number:标明音调 如ye1 1-4表示 1-4声
   * without_tone:不显示音调符 hanyupinyinvchartype :输出要用何种的拼音编码
   */
  public static string cntopinyin(string inputcn, string seg)
      throws badhanyupinyinoutputformatcombination {
    char[] inputarray = inputcn.tochararray();
    if (seg == null)
      seg = " ";
    hanyupinyinoutputformat format = new hanyupinyinoutputformat();
    format.setcasetype(hanyupinyincasetype.lowercase);
    format.settonetype(hanyupinyintonetype.without_tone);
    format.setvchartype(hanyupinyinvchartype.with_v);
    string output = "";
    string[] temp = new string[10];
    for (int i = 0; i < inputarray.length; i++) {
      temp = pinyinhelper.tohanyupinyinstringarray(inputarray[i], format);
      //若输入的汉字为多音字则会将不同的读音依次放入temp[]中,若不是多音字则只有temp[0]中有值
      for (int j = 0; j < temp.length; j++) {
        output += temp[j] + seg;
      }
    }
    return output;
  }
}

希望本文所述对大家java程序设计有所帮助。

如对本文有疑问, 点击进行留言回复!!

相关文章:

验证码:
移动技术网