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

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

参考文献

相关推荐
十年编程老舅7 天前
二本计算机,毕业=失业?
c++·程序员·编程·秋招·c++项目·春招·qt项目
远洋录16 天前
Ethan独立开发产品日报 | 2025-04-29
人工智能·程序员·副业·独立开发·赚钱
袁煦丞17 天前
Mdserver-web让服务器自由飞翔!:cpolar内网穿透实验室第590个成功挑战
前端·程序员·远程工作
考虑考虑17 天前
go使用gorilla/websocket实现websocket
后端·程序员·go
袁煦丞18 天前
每天省2小时!这个网盘神器让我告别云存储混乱(附内网穿透神操作)
前端·程序员·远程工作
袁煦丞18 天前
AI视频生成神器Wan 2.1:cpolar内网穿透实验室第596个成功挑战
人工智能·程序员·远程工作
程序员马晓博18 天前
还是聊聊吧:"大龄"程序员失业的一年
前端·程序员
京东云开发者18 天前
云交易技术对接全景
程序员
京东云开发者18 天前
自己写插件-实现时间戳自由
程序员
渭雨轻尘_学习计算机ing18 天前
二叉树构建算法全解析
算法·程序员