教你前端如何给文字添加拼音标注,包含声调展示及多音字处理

一、使用 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>

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值