简单实现汉字向拼音的转换

public class PinyinHelper {
	/**
	 * @param value
	 *            要转换成拼音的汉字
	 * @return 转换之后的字符串(拼音)数组
	 * @throws IOException
	 */
	public static String[] toPinyin(String value) {
		String[] pinyinArray = new String[value.length()];
		Map<String, String> map = toMap();
		// 读取value,得到对应的unicdoe值
		for (int i = 0; i < value.length(); i++) {
			Character character = value.charAt(i);
			// 转换成unicode
			String unicode = Integer.toHexString(character);
			unicode = unicode.toUpperCase();// 因为字库文件中是大写的
			String pinyin = map.get(unicode);
			pinyinArray[i] = pinyin;
		}
		return pinyinArray;
	}

	private static Map<String, String> toMap() {
		String line;// 用来保存每行读取的内容
		Map<String, String> map = new HashMap<String, String>();

		BufferedReader bufferedReader = null;
		try {
			InputStream is = PinyinHelper.class
					.getResourceAsStream("/pingyindb/unicode_to_hanyu_pinyin.txt");//读取jar包下文件的方法
			bufferedReader = new BufferedReader(new InputStreamReader(is));
			line = bufferedReader.readLine();
			while (line != null) {
				/**
				 * 可以用正则表达式简化
				 */
				String unicode = line.substring(0, 4);
				String pinyin = line.substring(6, line.length() - 1);
				map.put(unicode, pinyin);
				line = bufferedReader.readLine();
			}
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		} finally {

			try {
				bufferedReader.close();
			} catch (IOException e) {
				e.printStackTrace();
			}

		}
		return map;
	}

	public static void main(String[] args) {
		String[] s = toPinyin("今天天气不错啊!");
		for (String temps : s) {
			System.out.println(temps);
		}
	}
}


 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值