有的时候我们需要将中文转换成汉语拼音,将汉字转换成汉语拼音其实挺简单。首先我找到了一个资源,是一个XML文件:TBL_Dict.xml ,这个文件中每个汉字作为一个节点,该节点下有该汉字对应的汉语拼音,我的方法就是读取这个文件。
import java.util.List; import org.dom4j.Element; import com.yesoft.jdbcgeneric.constant.ConstantEnum; public class HzChangeToPy { /** * 将中文字符串转换成汉语拼音 * @param wenzi * @return */ public String toPinYin(String wenzi){ //XMLReader是一个读取xml文件的工具类,getRootElement()是将读取的xml文件内容返回为Element类型,这里我们解析xml使用的是dom4j。 XMLReader xmlReader = new XMLReader(ConstantEnum.PINYINXML.toString()); Element commonElement = xmlReader.getRootElement(); //Element wenziElement = commonElement.element("NewDataSet"); String pyStr = ""; List<Element> wenziList = commonElement.elements(); String[] str = chai(wenzi); for(int i = 0;i < str.length;i++){ for (Element el : wenziList) { String name = el.elementText("wenzi"); if (name.equals(str[i])) { pyStr += el.elementText("zimu"); } } } return pyStr; } /** * 将中文字符串拆解为单个字的数组 * @param wenzi * @return */ public String[] chai(String wenzi){ int length = wenzi.length(); String[] str = new String[length]; for(int i = 0;i<length;i++){ str[i] = wenzi.substring(i,i+1); } return str; } public static void main(String[] args){ HzChangeToPy py = new HzChangeToPy(); String srt = py.toPinYin("张三"); System.out.println(srt); } }这样张三就能转换成zhangsan了。下面是读取文件的工具类:
package com.yesoft.jdbcgeneric.utils; import java.io.File; import java.net.URLDecoder; import org.dom4j.Document; import org.dom4j.Element; import org.dom4j.io.SAXReader; import com.yesoft.jdbcgeneric.job.ScanDataSourceCountJob; public class XMLReader { private Document xmlDoc;// private Element root;// private String fileName; PropertiesUtil pu = new PropertiesUtil(); public XMLReader(String fileName) { this.fileName = fileName; readFile(); } private Document readFile() { try { if (xmlDoc == null) { String xmlClassPath = pu.readValueV("pyXmlPath"); // 使用SAXReader方式读取XML文件 SAXReader saxReader = new SAXReader(); String resourceListXmlPath = xmlClassPath + fileName; String realPath_resourceListXmlPath = ScanDataSourceCountJob.class .getResource(resourceListXmlPath).getFile(); realPath_resourceListXmlPath = URLDecoder.decode(realPath_resourceListXmlPath,"UTF-8"); File file = new File(realPath_resourceListXmlPath); // InputStream in = // ResourceXmlReader.class.getResourceAsStream(fileName); // 加载数据库XML配置文件,得到Document对象 // xmlDoc = saxReader.read(in); xmlDoc = saxReader.read(file); } } catch (Exception e) { e.printStackTrace(); } return xmlDoc; } public Document getXmlDoc() { return xmlDoc; } public void setXmlDoc(Document xmlDoc) { this.xmlDoc = xmlDoc; } public Element getRootElement() { if (root == null) { root = xmlDoc.getRootElement(); } return root; } }