java中文转拼音

简介

在我们使用手机通讯录或各种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));
  }

}

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

posted @ 2020-11-30 21:31  strongmore  阅读(13167)  评论(0编辑  收藏  举报