zoukankan      html  css  js  c++  java
  • 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));
      }
    
    }
    

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

  • 相关阅读:
    蓝桥杯训练 | 枚举,模拟与排序 | 04
    linux全套 | Linux模板机器安装 | 18
    linux全套 | Shell编程 | 16
    MySQL主从复制延迟解决方案
    MySQL异地备份方案
    MYSQL必知必会-where语句
    MySQL常见面试题-概念题
    入门-MySQL查询语句的45道练习
    20145234黄斐《信息安全系统设计基础》第0周学习总结
    OpenGL代码学习(2)
  • 原文地址:https://www.cnblogs.com/strongmore/p/14063899.html
Copyright © 2011-2022 走看看