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 ([email protected])