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

你可能感兴趣的:(grails,Pinyin)