Artikel ini menjelaskan metode Java untuk mengubah karakter Cina menjadi pinyin Cina. Bagikan untuk referensi Anda, sebagai berikut:
Saya berkeliaran di internet dan secara tidak sengaja melihat gadget yang sangat menarik yang disebut pinyin4j. Itu dapat mengubah karakter Cina menjadi pinyin Cina. Menggunakan kata -katanya dan dikombinasikan dengan Lucene dan China participle, Anda dapat membuat fungsi yang mirip dengan Google untuk memasukkan pinyin Cina untuk pencarian teks lengkap. Kode yang diimplementasikan adalah sebagai berikut
Paket pinyin4j; impor net.sourceForge.pinyin4j.pinyinhelper; impor net.sourceForge.pinyin4j.format.hanyupinyIsetype; impor net.sourceForge.pinyin4j.Format.hanyupinyinOutformat; impor net.sourceGege.pinyin4j.Format.hanyupinyinFormat; impor net.source.pinyine net.sourceforge.pinyin4j.format.HanyuPinyinVCharType;import net.sourceforge.pinyin4j.format.exception.BadHanyuPinyinOutputFormatCombination;public class pinyin4jTest { public static void main(String argsp[]) { try { String output = pinyin4jTest.CNToPinyin("Hello with you", null); System.out.println (output); } catch (badhanyupinyinOutputFormatcombination e) {// todo auto-generated catch block e.printstacktrace (); } } /** * @parm inputCN Chinese string input* @parm seg Delimiter when outputting Chinese pinyin* * HanyuPinyinOutputFormat provides several output modes* HanyuPinyinCaseType: Set whether the result of the input is uppercase or lowercase English LOWERCASE: lowercase UPPERCASE: uppercase * HanyuPinyinToneType: whether the output indicates the tone and the accent WITH_TONE_NUMBER: indicates the tone such as YE1 1-4, which means 1-4 sound* WITHOUT_TONE: The tone symbol is not displayed HanyuPinyinVCharType: What kind of pinyin encoding should be used for the output*/ public static String CNToPinyin(String inputCN, String seg) throws BadHanyuPinyinOutputFormatCombination { char[] inputArray = inputcn.tochararray (); if (seg == null) seg = ""; Format hanyupinyinOutputFormat = hanyupinyinOutputFormat baru (); format.setCasetype (hanyupinyincasetype.lowercase); format.settonetype (hanyupinyintonetype.without_tone); format.setVchartype (hanyupinyinvchartype.with_v); String output = ""; String [] temp = string baru [10]; untuk (int i = 0; i <inputArray.length; i ++) {temp = pinyinhelper.tohanyupinyInstringArray (inputArray [i], format); // Jika karakter Cina yang dimasukkan adalah karakter polifonik, pengucapan yang berbeda akan ditempatkan ke dalam suhu [] secara berurutan. Jika bukan karakter polifonik, hanya nilai dalam temp [0] untuk (int j = 0; j <temp.length; j ++) {output += temp [j] +seg; }} return output; }}Saya harap artikel ini akan membantu pemrograman Java semua orang.