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

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

参考文献

相关推荐
王霸天1 小时前
GLB 文件太大怎么办?我把它从 47MB 压到 8MB,全程没碰命令行
前端·javascript·程序员
SimonKing2 小时前
写文档的最佳搭档:Typora+PicList+SM.MS
java·后端·程序员
知了一笑3 小时前
没有项目经理的半年
程序员·产品·项目
AI小码1 天前
如何让AI帮你构建项目?七级方法
人工智能·算法·计算机·ai·程序员·大模型·编程
Hilaku1 天前
Web Components 为什么火不起来?
前端·javascript·程序员
newerp1 天前
语法分析与 AST:Parser 与 go/ast
后端·程序员·go
newerp1 天前
Go 编译过程全景
后端·程序员·go
SimonKing1 天前
Apache Fory JSON或许可以替代FastJson
java·后端·程序员
东风破_1 天前
Vibe Coding 上头之后,我开始用 SDD 给 AI 编程加一张“施工图”
人工智能·程序员
程序员cxuan2 天前
DeepSeek 多模态深度实测,确实有东西的
人工智能·后端·程序员