一、使用 JavaScript 拼音库自动转换
1. 使用 [pinyin-pro](https://github.com/zh-lx/pinyin-pro) 库
特点:支持多音字、声调、轻量级。
import { pinyin } from 'pinyin-pro';
// 获取带声调的拼音
const pinyinText = pinyin('汉语拼音', { toneType: 'symbol' });
// 输出: hàn yǔ pīn yīn
// 生成带拼音标注的 HTML
function addRubyAnnotations(text) {
return text.split('').map(char => {
const py = pinyin(char, { toneType: 'none', type: 'array' })[0] || '';
return `<ruby>${char}<rt>${py}</rt></ruby>`;
}).join('');
}
2. 使用 [pinyin](https://github.com/hotoo/pinyin) 库
特点:功能全面,支持自定义格式。
const pinyin = require('pinyin');
const result = pinyin('中文', {
style: pinyin.STYLE_TONE, // 带声调
heteronym: true // 多音字模式
});
// 输出: [ ['zhōng'], ['wén'] ]
二、HTML Ruby 标签手动标注
适用场景:静态内容、少量文字精确控制。
html
<ruby>
汉 <rt>hàn</rt>
字 <rt>zì</rt>
</ruby>
```
CSS 美化:
ruby rt {
font-size: 0.6em;
color: #666;
}
三、结合中文分词处理多音字
适用场景:需要上下文识别的复杂多音字场景。
使用 [segmentit](https://github.com/leizongmin/node-segment) 分词 + 拼音库
import { pinyin } from 'pinyin-pro';
import Segment from 'segmentit';
const segmentit = new Segment();
segmentit.useDefault();
const text = '银行的行长在行走';
const words = segmentit.doSegment(text);
const pinyinResult = words.map(word => pinyin(word.w, { toneType: 'none' })).join(' ');
// 输出: yin hang de hang zhang zai xing zou
四、调用第三方 API
// 示例:调用腾讯云 NLP 拼音转换 API
fetch('https://nlp.tencentcloudapi.com', {
method: 'POST',
body: JSON.stringify({ Text: '汉语拼音' })
})
.then(response => response.json())
.then(data => {
console.log(data.Pinyin);
});
五、Vue/React 组件封装
示例:React 拼音组件
jsx
import { pinyin } from 'pinyin-pro';
const PinyinText = ({ children }) => {
return (
<span>
{children.split('').map((char, index) => (
<ruby key={index}>
{char}
<rt>{pinyin(char, { toneType: 'none' })}</rt>
</ruby>
))}
</span>
);
};
// 使用
<PinyinText>你好世界</PinyinText>