首页 > 编程语言 > 详细

java中文转拼音

时间:2020-11-30 21:50:06      阅读:34      评论:0      收藏:0      [点我收藏+]

简介

在我们使用手机通讯录或各种APP的搜索功能时,既可以根据中文搜索,也可以根据拼音搜索,这种时候就使用到了中文转拼音的功能了。

实现

pinyin4j

引入maven依赖

<dependency>
   <groupId>com.belerweb</groupId>
   <artifactId>pinyin4j</artifactId>
   <version>2.5.1</version>
</dependency>

实例

public class Client {

  public static void main(String[] args) throws BadHanyuPinyinOutputFormatCombination {
    HanyuPinyinOutputFormat format = new HanyuPinyinOutputFormat();
    //拼音小写
    format.setCaseType(HanyuPinyinCaseType.LOWERCASE);
    //不带声调
    format.setToneType(HanyuPinyinToneType.WITHOUT_TONE);
    //要转换的中文,格式,转换之后的拼音的分隔符,遇到不能转换的是否保留   wo,shi,zhong,guo,ren,,hello
    System.out.println(PinyinHelper.toHanYuPinyinString("我是中国人,hello", format, ",", true));
  }

}

输出结果为

wo,shi,zhong,guo,ren,,hello

可以看到使用开源工具包实现中文转拼音还是很简单的。
技术分享图片
技术分享图片

其实就是将所有中文和对应的拼音保存起来并加载到内存中,转换时直接查找。

jpinyin

引入maven依赖

<dependency>
   <groupId>com.github.stuxuhai</groupId>
   <artifactId>jpinyin</artifactId>
   <version>1.1.8</version>
</dependency>

实例

public class Client {

  public static void main(String[] args) throws PinyinException {
    //要转换的中文,转换之后的拼音分隔符,拼音格式带声调  wǒshìzhōngguórén,hello
    System.out.println(
        PinyinHelper.convertToPinyinString("我是中国人,hello", "", PinyinFormat.WITH_TONE_MARK));
  }

}

技术分享图片

原理也是提前保存转换关系直接查询。

java中文转拼音

原文:https://www.cnblogs.com/strongmore/p/14063899.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!