当前位置:   article > 正文

Java 中文转拼音 pinyin4j 配置项详细介绍_java pinyin4j

java pinyin4j

Java 中文转拼音 pinyin4j 配置项详细介绍

1. jar包下载地址

链接:https://pan.baidu.com/s/1aRkPu8NTU8udxXdUNwOQUA
提取码:klrj

2. jar包导入到本地maven仓库

操作过程可以查看我的另一个文档, 里面介绍了如何将jar文件导入到maven仓库中
maven的jar包手动导入maven管理

3. 代码引用

<dependency>
    <groupId>com.github.open-android</groupId>
    <artifactId>pinyin4j</artifactId>
    <version>2.5.0</version>
</dependency>
  • 1
  • 2
  • 3
  • 4
  • 5

4. 配置项介绍

4.1 格式控制

HanyuPinyinOutputFormat format = new HanyuPinyinOutputFormat();   
  
// UPPERCASE:大写  (ZHONG)  
// LOWERCASE:小写  (zhong)  
format.setCaseType(HanyuPinyinCaseType.LOWERCASE);  
  
// WITHOUT_TONE:无音标  (zhong)  
// WITH_TONE_NUMBER:1-4数字表示英标  (zhong4)  
// WITH_TONE_MARK:直接用音标符(必须WITH_U_UNICODE否则异常)  (zhòng)  
format.setToneType(HanyuPinyinToneType.WITH_TONE_MARK);  
  
// WITH_V:用v表示ü  (nv)  
// WITH_U_AND_COLON:用"u:"表示ü  (nu:)  
// WITH_U_UNICODE:直接用ü (nü)  
format.setVCharType(HanyuPinyinVCharType.WITH_U_UNICODE);  
String[] pinyin = PinyinHelper.toHanyuPinyinStringArray('重', format); 
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16

5. 演示示例

public class PinYin4JTest {

   public static String getPinYin(String inputString) {  
          
       HanyuPinyinOutputFormat format = new HanyuPinyinOutputFormat();  
       format.setCaseType(HanyuPinyinCaseType.LOWERCASE);  
       format.setToneType(HanyuPinyinToneType.WITH_TONE_NUMBER);  
       format.setVCharType(HanyuPinyinVCharType.WITH_U_UNICODE);  
 
       char[] input = inputString.trim().toCharArray();  
       StringBuffer output = new StringBuffer("");  
 
       try {  
           for (int i = 0; i < input.length; i++) {  
               if (Character.toString(input[i]).matches("[\\u4E00-\\u9FA5]+")) {  
                   String[] temp = PinyinHelper.toHanyuPinyinStringArray(input[i], format);  
                   output.append(temp[0]);  
                   output.append(" ");  
               } else  
                   output.append(Character.toString(input[i]));  
           }  
       } catch (BadHanyuPinyinOutputFormatCombination e) {  
           e.printStackTrace();  
       }  
       return output.toString();  
   } 

	/**
	* @param args
	*/
	public static void main(String[] args) {
		// TODO Auto-generated method stub
		System.out.println(getPinYin("中华人民共和国"));
	}


}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37

5.1 输出结果

zhong1 hua2 ren2 min2 gong4 he2 guo2
  • 1

pinyin4j 我在使用时, 发现没有办法区分多音字, 例如 “还钱” 它会转换成 “hai2 qian2

商贾(gu)” 会转换成 “shang1 jia3

OVER 到此结束

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/花生_TL007/article/detail/596824
推荐阅读
相关标签
  

闽ICP备14008679号