当前位置:首页 > 开发 > Web前端 > 前端 > 正文

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

发表于: 2011-11-23   作者:热带翎羽   来源:转载   浏览:
摘要: 实现代码: package utility import net.sourceforge.pinyin4j.PinyinHelper import net.sourceforge.pinyin4j.format.* class PinyinService { static transactional = false static hanYuPinOutputFor
实现代码:
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)

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

  • 0

    开心

    开心

  • 0

    板砖

    板砖

  • 0

    感动

    感动

  • 0

    有用

    有用

  • 0

    疑问

    疑问

  • 0

    难过

    难过

  • 0

    无聊

    无聊

  • 0

    震惊

    震惊

版权所有 IT知识库 CopyRight © 2009-2015 IT知识库 IT610.com , All Rights Reserved. 京ICP备09083238号