java获取汉语拼音

获取汉语拼音

之前有个需求是要显示汉语拼音,然后找了一个工具包

xml 复制代码
<!-- 汉语拼音 -->
<dependency>
    <groupId>com.belerweb</groupId>
    <artifactId>pinyin4j</artifactId>
    <version>2.5.1</version>
</dependency>

来个栗子

java 复制代码
HanyuPinyinOutputFormat hanyuPinyinOutputFormat = new HanyuPinyinOutputFormat();
hanyuPinyinOutputFormat.setToneType(WITHOUT_TONE);
System.out.println(PinyinHelper.toHanYuPinyinString("北京市", hanyuPinyinOutputFormat, "", true));

// 输出 beijingshi

但是有时候是多音字的怎么处理的,比如长沙市

java 复制代码
HanyuPinyinOutputFormat hanyuPinyinOutputFormat = new HanyuPinyinOutputFormat();
hanyuPinyinOutputFormat.setToneType(WITHOUT_TONE);
System.out.println(PinyinHelper.toHanYuPinyinString("长沙市", hanyuPinyinOutputFormat, "", true));

// 输出 zhangshashi

这结果也不对呀

多音字处理

当然是有解决方案的,该工具提供了一个外挂,可以自定义一些词的多音字组合

如我配置了长沙在一块的话读changsha

scss 复制代码
长沙 (chang2,sha1)

然后使用该外挂

java 复制代码
HanyuPinyinOutputFormat hanyuPinyinOutputFormat = new HanyuPinyinOutputFormat();
hanyuPinyinOutputFormat.setToneType(WITHOUT_TONE);
MultiPinyinConfig.multiPinyinPath=Thread.currentThread().getContextClassLoader().getResource("pinyindb/multipy.txt").getPath();
System.out.println(PinyinHelper.toHanYuPinyinString("长沙市", hanyuPinyinOutputFormat, "", true));

// 输出  changshashi

后续的多音字直接在该文件中加入就行

参考文献

相关推荐
一晌小贪欢13 小时前
Python 异步编程深度解析:从生成器到 Asyncio 的演进之路
开发语言·python·程序员·python基础·python小白·python测试
京东云开发者1 天前
如何使用wireshark进行远程抓包
程序员
京东云开发者1 天前
InheritableThreadLocal从入门到放弃
程序员
京东云开发者1 天前
🔥1篇搞懂AI通识:大白话拆解核心点
程序员
掘金安东尼1 天前
向大家介绍《开发者博主联盟》🚀
前端·程序员·github
Iqnus1 天前
WSL安装记录(自用)
程序员
陈随易1 天前
聊一聊2025年用AI的思考与总结
前端·后端·程序员
陈随易2 天前
Vue-Router v5内置文件式路由,告别手写维护的恐惧
前端·后端·程序员
SimonKing2 天前
基于Netty的WebSocket自动解决拆包粘包问题
java·后端·程序员
Baihai_IDP2 天前
智能体的构建依然是个“脏活累活”...
人工智能·程序员·llm