Finally, Chinese Pinyin can be displayed automatically on html

Keywords: Programming Ruby JQuery Java github

In the last article html articles showing phonetic labels In it, I was also mistaken at first. As long as the <ruby>tag is added, the spelling of Chinese characters can be displayed automatically. But obviously, this is only a good idea. In fact, what to spell depends on your own manual work, but in the programmer's world, there is always a way. This is how to automatically spell Chinese characters.

Warning: This backend article, after all, I'm mainly engaged in java programming.

1. Find Open Source

Actually, the first thing is to find an open source software that can turn Chinese characters into Pinyin, so I found it (java is that good, what to do). jpinyin I can't find its link on github. There's another jpinyin address, but I don't know if it's the same.But it does spell the phonetic characters with tones.However, its own source code can be downloaded directly from maven, so it is safe to use.

2. Use it

I'm using spring boot, so I introduced jpinyin's jar in pom.xml.


Then use jpinyin's Chinese character conversion and the html Chinese phonetic fragment I need to make it

private String pinyinHtml(String str) {
		String py = PinyinHelper.convertToPinyinString(str, "|", PinyinFormat.WITH_TONE_MARK);
		char[] charArray = str.toCharArray();
		String[] pyArray = py.split("\\|");
		String returnStr = "";
		int j = 0;
		for(int i=0;i<pyArray.length;i++) {
			if(ChineseHelper.isChinese(charArray[j])) {
			}else {
				for(int k=j;k<charArray.length;k++) {
					returnStr +=charArray[k];
		return returnStr;

This section mainly uses jpinyin to convert Chinese characters to Pinyin. It should be noted that considering the possible input string is not only Chinese, but also may be confusing content, we have done some processing to make the Chinese characters have Pinyin labels, other strings are not. Look at the effect video above, which demonstrates the situation of confusing strings.

Then we'll have a page demo of this:

<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1">
<link href="" rel="stylesheet">
<script src=""></script>
<div class="container">
<div class="form-group">
<textarea id="hanzi" rows="3" >
<div class="form-group">
<input id="magic" type="button" value="Miracle moment" />
<h3 id="miracle"></h3>

Read the html fragment through jquery's ajax, show it, this open source software phonetic recognition is still good, but the multi-syllable word is no longer possible, you can enter "parachute surrendered" to try.

This is complete Demo Code Welcome to Star

Posted by gotissues68 on Thu, 07 Nov 2019 06:47:01 -0800