当前位置: 首页 > 工具软件 > pinyin4js > 使用案例 >

pinyin4j 中文字符串转换成拼音简略输出 - 代码共享

长孙谦
2023-12-01
[代码] pinyin4j是一个撑持将简体和繁体中文转换成拼音的Java开源类库. package com.wang;

import net.sourceforge.pinyin4j.PinyinHelper;
import net.sourceforge.pinyin4j.format.HanyuPinyinCaseType;
import net.sourceforge.pinyin http://www.fpnanchang.com/linked/20130206.do; 4j.format.HanyuPinyinOutputFormat;
import net.sourceforge.pinyin4j.format.HanyuPinyinToneType;
import net.sourceforge.pinyin4j.format.HanyuPinyinVCharType;
import net.sourceforge.pinyin4j.format.exception.BadHanyuPinyinOutputFormatCombination;

public class PinYinTest {

	public static String getPinYin(String strs) {

		HanyuPinyinOutputFormat format = new HanyuPinyinOutputFormat();
		format.setCaseType(HanyuPinyinCaseType.LOWERCASE);
		format.setToneType(HanyuPinyinToneType.WITH_TONE_MARK);
		format.setVCharType(HanyuPinyinVCharType.WITH_U_UNICODE);
		char[] ch = strs.trim().toCharArray();
		StringBuffer buffer = new StringBuffer("");

		try {
			for (int i = 0; i < ch.length; i  ) {
				// unicode,bytes应该也能够.
				if (Character.toString(ch[i]).matches("[\u4e00-\u9fa5] ")) {
					String[] temp = PinyinHelper.toHanyuPinyinStringArray(
							ch[i], format);
					buffer.append(temp[0]);// :成果"?"现已查出,可是腔调是3声时不显现myeclipse8.6和eclipse
					buffer.append(" ");
				} else {
					buffer.append(Character.toString(ch[i]));
				}
			}
		} catch (BadHanyuPinyinOutputFormatCombination e) {
			e.printStackTrace();
		}
		return buffer.toString();
	}

	public static void main(String[] args) {
		String chstrs = "好想家! Good homesick!";
		System.out.println("输入:"   chstrs);
		System.out.println("成果:"   getPinYin(chstrs));
	}

} http://www.szhaoexport.com/linked/20130206.do;

转载于:https://www.cnblogs.com/fpqqchao/archive/2013/02/07/2908803.html

 类似资料: