import com.google.common.base.Strings;
import net.sourceforge.pinyin4j.PinyinHelper;
import net.sourceforge.pinyin4j.format.HanyuPinyinOutputFormat;
import net.sourceforge.pinyin4j.format.HanyuPinyinToneType;
import net.sourceforge.pinyin4j.format.exception.BadHanyuPinyinOutputFormatCombination;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory; import java.util.ArrayList;
import java.util.List;
import java.util.Locale;
import java.util.TreeSet; public class PinyinUtils {
private static final Logger logger = LoggerFactory.getLogger(PinyinUtils.class); /**
* 单字解析
*
* @param str first
* @return
*/
public static String[] convert(String str) {
String[] reslut = null;
HanyuPinyinOutputFormat hanyuPinyinOutputFormat = new HanyuPinyinOutputFormat();
hanyuPinyinOutputFormat.setToneType(HanyuPinyinToneType.WITHOUT_TONE);
try {
reslut = PinyinHelper.toHanyuPinyinStringArray(str.charAt(0), hanyuPinyinOutputFormat);
TreeSet<String> stringTreeSet = new TreeSet<>();
for (int i = 0; i < reslut.length; i++) {
if(reslut.length >=3) {
break;
}
stringTreeSet.add(reslut[i].replace("u:","v"));
}
reslut = new String[stringTreeSet.size()];
reslut = stringTreeSet.toArray(reslut);
} catch (BadHanyuPinyinOutputFormatCombination badHanyuPinyinOutputFormatCombination) {
badHanyuPinyinOutputFormatCombination.printStackTrace();
} catch (Exception e) {
logger.error("[convert]: ", e);
}
return reslut;
} /**
* 词组解析(全写)
*
* @param chs
* @return
*/
public static String getSelling(String chs) {
return translate(chs, false);
} /**
* 汉字转拼音
*
* @param chs
* @param acronym
* @return
*/
private static String translate(String chs, boolean acronym) {
StringBuffer buffer=new StringBuffer();
if (Strings.isNullOrEmpty(chs))
return "";
try {
List<List<String>> temps = new ArrayList<>();
int len = chs.length();
int len1 = 0;
for (int i = 0; i < len; i++) {
List<String> stringList = new ArrayList<>();
String key = chs.charAt(i) + "";
if (key.getBytes().length >= 2) {
String[] temp = convert(key);
if(temp.length == 0) {
continue;
}
if (temp == null) {
stringList.add("");
} else {
for (String v : temp) {
stringList.add(v);
}
}
} else {
stringList.add(key);
}
temps.add(stringList);
len1++;
}
List<List<String>> t = new ArrayList<>();
for (int i = 0; i < len1; i++) {
List<String> currentList = new ArrayList<>();
List<String> stringList = temps.get(i);
if (stringList != null) {
for (String s : stringList) {
if (acronym) {
s = s.charAt(0) + "";
}
if (i > 0) {
List<String> preList = t.get(i - 1);
if (preList != null) {
for (String s1 : preList) {
currentList.add(s1 + s);
}
}
}else{
currentList.add(s);
}
}
}
t.add(i, currentList);
}
if (t.size()>0){
List<String> currentList= t.get(t.size()-1);
if (currentList!=null){
for(String current : currentList){
buffer.append(current);
buffer.append("");
}
}
}
return buffer.toString();
} catch (Exception e) {
logger.error("[getSortLetters]: ", e);
return "";
}
} /**
* 词组解析(缩写)
*
* @param chs
* @return
*/
public static String getSmallSelling(String chs) {
return translate(chs, true);
} /**
* 获取首字母
*
* @return
*/
public static String getSortLetters(String pingyin) {
try {
String sortString = pingyin.substring(0, 1).toUpperCase(Locale.getDefault());
// 正则表达式,判断首字母是否是英文字母
if (sortString.matches("[A-Z]")) {
return sortString.toUpperCase(Locale.getDefault());
}
} catch (Exception e) {
logger.error("[getSortLetters]: ", e);
}
return "#";
} public static void main(String [] args) {
PinyinUtils p = new PinyinUtils(); System.out.println(p.getSelling("单个"));
System.out.println(p.getSmallSelling("测试"));
}
}

java汉字转拼音的工具类的更多相关文章

  1. Java汉字转成汉语拼音工具类

    Java汉字转成汉语拼音工具类,需要用到pinyin4j.jar包. import net.sourceforge.pinyin4j.PinyinHelper; import net.sourcefo ...

  2. Java操作文件夹的工具类

    Java操作文件夹的工具类 import java.io.File; public class DeleteDirectory { /** * 删除单个文件 * @param fileName 要删除 ...

  3. java中excel导入\导出工具类

    1.导入工具 package com.linrain.jcs.test; import jxl.Cell; import jxl.Sheet; import jxl.Workbook; import ...

  4. java中定义一个CloneUtil 工具类

    其实所有的java对象都可以具备克隆能力,只是因为在基础类Object中被设定成了一个保留方法(protected),要想真正拥有克隆的能力, 就需要实现Cloneable接口,重写clone方法.通 ...

  5. java代码行数统计工具类

    package com.syl.demo.test; import java.io.*; /** * java代码行数统计工具类 * Created by 孙义朗 on 2017/11/17 0017 ...

  6. Java加载Properties配置文件工具类

    Java加载Properties配置文件工具类 import org.apache.commons.lang3.StringUtils; import org.apache.log4j.Logger; ...

  7. Java 操作Redis封装RedisTemplate工具类

    package com.example.redisdistlock.util; import org.springframework.beans.factory.annotation.Autowire ...

  8. java后台表单验证工具类

    /** * 描述 java后台表单验证工具类 * * @ClassName ValidationUtil * @Author wzf * @DATE 2018/10/27 15:21 * @VerSi ...

  9. 【转】Java压缩和解压文件工具类ZipUtil

    特别提示:本人博客部分有参考网络其他博客,但均是本人亲手编写过并验证通过.如发现博客有错误,请及时提出以免误导其他人,谢谢!欢迎转载,但记得标明文章出处:http://www.cnblogs.com/ ...

随机推荐

  1. 通过 thread dump 分析找到高CPU耗用与内存溢出的Java代码

    http://heylinux.com/archives/1085.html通过 thread dump 分析找到高CPU耗用与内存溢出的Java代码 首先,要感谢我的好朋友 钊花 的经验分享. 相信 ...

  2. kettle--组件(2)--计算器

    组件如下: 对计算类型的说明如下: The table below contains descriptions associated with the calculator step: Functio ...

  3. hihoCoder[Offer收割]编程练习赛1题目解析

    题目1 : 九宫 时间限制:10000ms 单点时限:1000ms 内存限制:256MB 描写叙述 小Hi近期在教邻居家的小朋友小学奥数.而近期正好讲述到了三阶幻方这个部分,三阶幻方指的是将1~9不反 ...

  4. FreeSWITCH技巧:notify与message-waiting

    FreeSWITCH技巧:notify与message-waiting @(Freeswitch经验点滴) 现象描述 在客户端登陆抓包时,发现了FreeSWITCH发来的包: NOTIFY sip:9 ...

  5. redis conf 详解

    2.8配置 # Redis configuration file example # Note on units: when memory size is needed, it is possible ...

  6. unity的自带特性

    2016/9/24补充: unity官方有一篇文章对菜单扩展讲的不错 https://unity3d.com/cn/learn/tutorials/topics/interface-essential ...

  7. maven学习资料

    maven学习资料 maven学习教程:What.How.Whyhttp://www.flyne.org/article/167 Maven 那点事儿 https://my.oschina.net/h ...

  8. 把一个project相关的jar放到project的lib文件夹中

    例如你有一个project名为xxx,/xxx 文件夹中有src.bin.等等,然后你手工创建一个lib文件夹,这样你就把解压出来的第三方lib(jar包,含javadoc)都放到lib文件夹中,这样 ...

  9. iOS 新手引导页图片适配及其尺寸大全

    早期新手引导页只需要几张图片就可以解决了,随着屏幕尺寸的的越来越多,新手引导页的尺寸适配起来越来越麻烦,否则就会出现尺寸不匹配,图片被拉伸的情况 目前应该是有2种方法来解决这个问题 方法1: 根据每款 ...

  10. 跟着百度学PHP[14]-PDO的错误处理模式&PDO执行SQL

    我们在使用PDO去执行sql语句的时候并不会报错.如下案例所示: <?php try { //$pdo = new pdo("mysql:host=主机;port=端口;dbname= ...