创建Grails的中文拼音转换服务

实现代码:

package utility
import net.sourceforge.pinyin4j.PinyinHelper
import net.sourceforge.pinyin4j.format.*
class PinyinService {

static transactional = false
static hanYuPinOutputFormat=null
def init()
{
hanYuPinOutputFormat = new HanyuPinyinOutputFormat();
hanYuPinOutputFormat.setCaseType(HanyuPinyinCaseType.LOWERCASE);
hanYuPinOutputFormat.setToneType(HanyuPinyinToneType.WITHOUT_TONE)
hanYuPinOutputFormat.setVCharType(HanyuPinyinVCharType.WITH_V);
}
//如: convertToList("福州")=["fu", "zhou"]
def convertToList(String chinese) {

if(hanYuPinOutputFormat==null) init()
def pinyin = []
chinese.getChars().each {
if(it > 128)
{
pinyin.add( PinyinHelper.toHanyuPinyinStringArray(it,hanYuPinOutputFormat)[0])
}
}
return pinyin
}

//如: convertToString("福州")="FuZhou"
def convertToString(String chinese) {
if(hanYuPinOutputFormat==null) init()

def pinyin = ""
chinese.getChars().each {
if(it > 128)
{
pinyin=pinyin+ (PinyinHelper.toHanyuPinyinStringArray(it,hanYuPinOutputFormat)[0]).capitalize()
}
}
return pinyin
}

//如: convertToAbbreviationString("福州")="FZ"
def convertToAbbreviationString(String chinese) {
if(hanYuPinOutputFormat==null) init()

def pinyin = ""
chinese.getChars().each {
if(it > 128)
{
pinyin=pinyin+ PinyinHelper.toHanyuPinyinStringArray(it,hanYuPinOutputFormat)[0][0].capitalize()
}
}
return pinyin
}
}



测试代码:


class BootStrap {
def pinyinService
def init = { servletContext ->
println "Start pinyin testing:"

println "中国福州 to list:"+" "+pinyinService.convertToList("中国福州")
println "中国福州 to string:"+" "+pinyinService.convertToString("中国福州")
println "中国福州 to abbreviation string:"+" "+pinyinService.convertToAbbreviationString("中国福州")

println "End pinyin testing."
}
def destroy = {
}
}


运行结果:


Start pinyin testing:
中国福州 to list: [zhong, guo, fu, zhou]
中国福州 to string: ZhongGuoFuZhou
中国福州 to abbreviation string: ZGFZ
End pinyin testing.


感谢pinyin4j作者:Li Min (xmlerlimin@gmail.com)
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值