pinyin-pro Documentation

中文转拼音、拼音音调、拼音声母、拼音韵母、多音字拼音、姓氏拼音、拼音匹配、中文分词

4,748 stars TypeScript TypeScript 50 files · ~49,466 tokens #hanzi#hanzi-pinyin#hanzi2pinyin#js-pinyin#pinyin#pinyin-match#pinyin-pro
RAW Doc

Technical Documentation: zh-lx/pinyin-pro

ℹ️ Provenance: Multi-Tier Ingestion · CodeWiki Reference

Overview (`packages/data/README.md`)

pinyin-pro-data

📖 介绍

[pinyin-pro] 的官方扩充字典包。目前包含的包如下:

🔨 安装

选择合适的包管理器

shell
npm install @pinyin-pro/data
yarn add @pinyin-pro/data
pnpm add @pinyin-pro/data

💡 使用示例

使用扩展字典:

js
import CharsDict from '@pinyin-pro/data/chars';
import { addDict } from 'pinyin-pro';

addDict(CharsDict);

使用完备字典:

js
import { addDict } from 'pinyin-pro';
import CompleteDict from '@pinyin-pro/data/complete';
addDict(CompleteDict);

使用现代汉语词典:

js
import { addDict } from 'pinyin-pro';
import ModernDict from '@pinyin-pro/data/modern';
addDict(ModernDict);

使用佛经词典(处理佛典文本时再加载,不影响默认读音):

js
import { addDict } from 'pinyin-pro';
import BuddhistDict from '@pinyin-pro/data/buddhist';
addDict(BuddhistDict);

Overview (`packages/docs/README.md`)

pinyin-pro-doc

pinyin-pro 在线文档,欢迎访问 pinyin-pro


Overview (`packages/pinyin-pro/README.md`)









📖 介绍

pinyin-pro 是一个专业的 js 汉字拼音转换库,功能丰富、准确率高、性能优异。

中文文档 | English Docs | 在线运行

🎨 特色功能

  • 支持拼音/声母/韵母/首字母/音调/全部信息
  • 支持人名姓氏模式
  • 支持文本和拼音匹配
  • 支持自定义拼音
  • 支持获取带拼音汉字的 HTML 字符串
  • 支持获取汉字的所有拼音
  • 支持拼音输入转换
  • 极致的性能和极高的拼音识别准确率

🔨 安装

npm 安装

html
npm install pinyin-pro

浏览器引入

html
<script src="https://unpkg.com/pinyin-pro"></script>

💡 使用示例

全部功能的使用说明文档请查看在线文档

  • 获取拼音,更多功能请查看pinyin API

    js
    import { pinyin } from "pinyin-pro";
    
    // 获取字符串格式拼音
    pinyin("汉语拼音"); // 'hàn yǔ pīn yīn'
    
    // 获取数组格式拼音
    pinyin("汉语拼音", { type: "array" }); // ["hàn", "yǔ", "pīn", "yīn"]
    
    // 获取不带音调格式拼音
    pinyin("汉语拼音", { toneType: "none" }); // "han yu pin yin"
    
    // 获取不带音调数组格式拼音
    pinyin("汉语拼音", { toneType: "none", type: "array" }); // ["han", "yu", "pin", "yin"]
    
    // 音调以数字形式显示
    pinyin("汉语拼音", { toneType: "num" }); // "han4 yu3 pin1 yin1"
    
    // 自动识别多音字
    pinyin("睡着了"); // "shuì zháo le"
  • 文本和拼音匹配,更多匹配规则请查看match API

    点击展开文本和拼音匹配示例

    js
    import { match } from "pinyin-pro";
    
    // 支持首字母匹配
    match("中文拼音", "zwp"); // [0, 1, 2]
    
    // 支持全拼匹配
    match("中文拼音", "zhongwenpin"); // [0, 1, 2]
    
    // 支持混合匹配
    match("中文拼音", "zhongwp"); // [0, 1, 2]
  • 拼音格式转换,更多功能请查看convert API

    点击展开拼音格式转换示例

    js
    import { convert } from "pinyin-pro";
    
    // 数组转符号
    convert("pin1 yin1"); // 'pīn yīn'
    
    // 符号转数字
    convert("pīn yīn", { format: "symbolToNum" }); // 'pin1 yin1'
    
    // 消除符号
    convert("pīn yīn", { format: "toneNone" }); // 'pin yin'
    
    // 儿化音
    convert("dou4 zhi1r") // dòu zhīr
    convert("dòu zhīr", { format: "symbolToNum" }) // dou4 zhi1r
    convert("dòu zhīr", { format: "toneNone" }); // 'dou zhir'
  • 分词并获取拼音,更多配置请查看segment API

    点击展开 segment 基础使用示例

    js
    import { segment, OutputFormat } from "pinyin-pro";
    
    // 默认返回分词及对应的拼音
    segment("我喜欢学习汉语");
    // [
    //   { origin: "我", result: "wǒ" },
    //   { origin: "喜欢", result: "xǐhuān" },
    //   { origin: "学习", result: "xuéxí" },
    //   { origin: "汉语", result: "hànyǔ" }
    // ]
    
    // 仅获取分词后的拼音
    segment("我喜欢学习汉语", { format: OutputFormat.PinyinString });
    // "wǒ xǐhuān xuéxí hànyǔ"
  • 获取带汉字拼音的 HTML 字符串,更多配置请查看html API

    点击展开 HTML 字符串示例

    js
    import { html } from "pinyin-pro";
    
    // 带拼音汉字的 HTML 字符串
    html("汉语拼音");
    /*
    <span class="py-result-item">
    <ruby>
        <span class="py-chinese-item">汉</span>
        <rp>(</rp>
        <rt class="py-pinyin-item">hàn</rt>
        <rp>)</rp>
    </ruby>
    </span>
    <span class="py-result-item">
    <ruby>
        <span class="py-chinese-item">语</span>
        <rp>(</rp>
        <rt class="py-pinyin-item">yǔ</rt>
        <rp>)</rp>
    </ruby>
    </span>
    */

    上述结果浏览器中预览效果如下:

    汉 ( hàn ) 语 ( yǔ )
  • 更多的 API 请查看pinyin-pro 官网

🏆 竞品对比

以下是 pinyin-pro、pinyin 及 @napi-rs/pinyin 包对于汉字转换的速度及准确率对比,可以看到 pinyin-pro 在各方面都全面领先。

对比项 pinyin @napi-rs/pinyin pinyin-pro
准确率 😕 Node 版: 94.097% 😕 94.097% 🤩 99.846%
😕 Web 版: 91.170%
性能 首次使用字典初始化时长 🚀 14.261ms 🐢 160.769ms 🚀 8.412ms
10k字转换耗时 🚲 74.442ms 🚀 4.298ms 🚀 7.216ms
100k字转换耗时 🐢 6287.332ms 🚀 29.32ms 🚀 45.471ms
1m字转换耗时 ⛔ 内存溢出转换失败 🚀 297.41ms 🚀 328.338ms
10m字转换耗时 ⛔ 内存溢出转换失败 🚀 3907.278ms 🚀 3375.192ms
兼容性 Web 环境 ✔️ 支持 ❌ 不支持 ✔️ 支持
Node 环境 ✔️ 支持 ✔️ 支持 ✔️ 支持

📦 API Size

以下数据由 pnpm size 自动生成。ESM 各 API 为独立打包并开启 Tree Shaking 后的压缩体积;UMD 不支持按 API Tree Shaking,展示完整产物体积。括号内为对应产物 gzip 后的体积。

API ESM UMD
pinyin 307.03 KB (gzip 134.83 KB) 317.47 KB (gzip 138.33 KB)
segment 305.79 KB (gzip 134.04 KB)
match 185.67 KB (gzip 80.90 KB)
convert 1.78 KB (gzip 0.98 KB)
html 307.87 KB (gzip 135.13 KB)
polyphonic 180.75 KB (gzip 78.83 KB)
总体积 561.18 KB (gzip 158.13 KB)

📠 反馈

使用遇到问题或者需要功能支持欢迎提 issue。

技术交流欢迎加 pinyin-pro 用户群 或者微信:

🧰 Monorepo 开发

本仓库使用 pnpm workspace 管理以下项目:

  • packages/pinyin-pro:pinyin-pro 核心包
  • packages/data:@pinyin-pro/data 扩展字典包及数据处理脚本
  • packages/docs:中英文 VitePress 文档
shell
pnpm install
pnpm build          # 构建核心包与数据包
pnpm test           # 运行核心包测试
pnpm build:docs     # 构建并打包中英文文档
pnpm build:all      # 构建全部 workspace
pnpm docs:dev:zh    # 启动中文文档
pnpm docs:dev:en    # 启动英文文档

Packages Docs En Docs Index (`packages/docs/en/docs/index.md`)


https://vitepress.dev/reference/default-theme-home-page

layout: home

hero:
name: pinyin-pro
text: Professional in pinyin
tagline: A Chinese pinyin conversion library with accurate recognition and excellent performance
image:
src: /images/logo-circle.svg
alt: pinyin-pro
actions:
- theme: brand
text: Get Started
link: /guide/start
- theme: alt
text: Examples
link: /use/pinyin

features:

  • title: 🎨 Rich Functionality
    details: Rich and diverse functions, including but not limited to Chinese Pinyin conversion, Segment, Chinese Pinyin matching, and Chinese Pinyin HTML strings
  • title: 🚀 Excellent Performance
    details: By applying algorithms such as AC automata, greedy algorithm, and hash function optimization, the performance is greatly excellent
  • title: 🔍 Accurate Recognition
    details: Having a massive data processed Chinese Pinyin database, the accuracy of pinyin conversion is extremely high


Packages Docs Zh Docs Index (`packages/docs/zh/docs/index.md`)


https://vitepress.dev/reference/default-theme-home-page

layout: home

hero:
name: pinyin-pro
text: 专业的拼音转换工具
tagline: 一个识别准确、性能优异的汉字拼音转换库
image:
src: /images/logo-circle.svg
alt: pinyin-pro
actions:
- theme: brand
text: 快速开始
link: /guide/start
- theme: alt
text: 使用示例
link: /use/pinyin

features:

  • title: 🎨 功能丰富
    details: 具备中文拼音转换、中文拼音匹配、分词、带拼音中文格式 HTML 字符串转换等丰富的功能
  • title: 🚀 性能优异
    details: 通过高效的 AC 自动机算法 + 最大匹配算法,可在 1 秒内完成数百万规模中文拼音的转换
  • title: 🔍 识别准确
    details: 支持最高概率/最大匹配/最小分词数等多种可选算法,结合完备的数据词典,识别率非常准确


Packages Docs Package.Json (`packages/docs/package.json`)

{
"name": "@pinyin-pro/docs",
"private": true,
"scripts": {
"build": "pnpm --filter @pinyin-pro/docs-en docs:build && pnpm --filter @pinyin-pro/docs-zh docs:build && node scripts/zip.js"
},
"devDependencies": {
"fs-extra": "^11.2.0",
"zip-a-folder": "^3.1.7"
}
}


Packages Docs En Package.Json (`packages/docs/en/package.json`)

{
"name": "@pinyin-pro/docs-en",
"private": true,
"scripts": {
"docs:dev": "vitepress dev",
"docs:build": "vitepress build",
"docs:preview": "vitepress preview"
},
"devDependencies": {
"less": "^4.2.0",
"prismjs": "^1.29.0",
"pinyin-pro": "workspace:^",
"vitepress": "1.0.0-rc.25",
"vue": "^3.3.8"
}
}


Packages Docs Zh Package.Json (`packages/docs/zh/package.json`)

{
"name": "@pinyin-pro/docs-zh",
"private": true,
"scripts": {
"docs:dev": "vitepress dev",
"docs:build": "vitepress build",
"docs:preview": "vitepress preview"
},
"devDependencies": {
"less": "^4.2.0",
"prismjs": "^1.29.0",
"pinyin-pro": "workspace:^",
"vitepress": "1.0.0-rc.25",
"vue": "^3.3.8"
}
}


Packages Pinyin Pro Docs 1.2.X (`packages/pinyin-pro/docs/1.2.x.md`)

pinyin-pro 中文转换拼音库(支持获取汉字、词语、句子的拼音、音调、声母、韵母多种形式)

中文转换拼音库,支持获取汉字、词语、句子等多种内容的拼音、音调、声母、韵母等。通过高效的算法和丰富的字词库,保证体积轻量的同时识别准确率很高。

安装

npm 安装

text
npm install pinyin-pro

yarn 安装

text
yarn add pinyin-pro

使用

浏览器端:

javascript
import { pinyin } from 'pinyin-pro';

node 端:

javascript
const { pinyin } = require('pinyin-pro');

参数

pinyin(word, options) 接收两个参数

  • **word:**必填。String 类型,需要转化为拼音的中文
  • **options:**可选。Object 类型,用于配置各种输出形式,相关配置在后面有所介绍

基本用法

javascript
import { pinyin } from 'pinyin-pro'; // 若为node环境请用require形式引入

// 获取带音调拼音
pinyin('汉语拼音'); // 'hàn yǔ pīn yīn'
// 获取不带声调的拼音
pinyin('汉语拼音', { tone: false }); // 'han yu pin yin'
// 获取声调转换为数字后缀的拼音
pinyin('汉语拼音', { pattern: 'pinyinNum' }); // 'han4 yu3 pin1 yin1'
// 获取声母
pinyin('汉语拼音', { pattern: 'initial' }); // 'h y p y'
// 获取带音调韵母
pinyin('汉语拼音', { pattern: 'final' }); // 'àn ǔ īn īn'
// 获取不带音调韵母
pinyin('汉语拼音', { pattern: 'final', tone: false }); // 'an u in in'
// 获取音调
pinyin('汉语拼音', { pattern: 'num' }); // '4 3 1 1'

结果输出为数组格式

通过在 options 参数中加入type: 'array',可以以数组形式输出基本用法中的示例:

javascript
// 获取带音调拼音
pinyin('汉语拼音', { type: 'array' }); // ["hàn", "yǔ", "pīn", "yīn"]
// 获取不带声调的拼音
pinyin('汉语拼音', { tone: false, type: 'array' }); // ["han", "yu", "pin", "yin"]
// 获取声调转换为数字后缀的拼音
pinyin('汉语拼音', { pattern: 'pinyinNum', type: 'array' }); // ["han4", "yu3", "pin1", "yin1"]
// 获取声母
pinyin('汉语拼音', { pattern: 'initial', type: 'array' }); // ["h", "y", "p", "y"]
// 获取带音调韵母
pinyin('汉语拼音', { pattern: 'final', type: 'array' }); // ["àn", "ǔ", "īn", "īn"]
// 获取不带音调韵母
pinyin('汉语拼音', { pattern: 'final', tone: false, type: 'array' }); // ["an", "u", "in", "in"]
// 获取音调
pinyin('汉语拼音', { pattern: 'num', type: 'array' }); // ["4", "3", "1", "1"]

获取单个字的多音

只有单字可以获取到多音模式, 词语、句子无效。同样可以通过配置 options 选项获取数组形式、韵母等格式

javascript
pinyin('好', { multiple: true }); // 'hǎo hào'
pinyin('好', { multiple: true, type: 'array' }); // ["hǎo", "hào"]

options 配置

参数 说明 类型 可选值 默认值
pattern 输出的结果的信息(带音调全拼 / 音调为数字后缀的全拼 / 声母 / 韵母 / 音调) string pinyin / pinyinNum / initial / final / num pinyin
tone 是否开启音调(为 true 时会覆盖 pattern 中的音调) boolean true / false true
type 输出结果类型(字符串/数组) string string / array string
multiple 输出多音字全部拼音(仅在 word 为单字时生效) boolean true / false false

交流与反馈

有问题或者功能需求支持欢迎提 issue


Packages Pinyin Pro Docs 2.0.X (`packages/pinyin-pro/docs/2.0.x.md`)

pinyin-pro 汉字拼音转换工具(支持获取汉字、词语、句子的拼音、音调、声母、韵母多种形式)

汉字拼音转换工具,支持获取汉字、词语、句子等多种内容的拼音、音调、声母、韵母等。通过高效的算法和丰富的字词库,保证体积轻量的同时识别准确率很高。

安装

npm 安装

text
npm install pinyin-pro

yarn 安装

text
yarn add pinyin-pro

使用

浏览器端:

javascript
import { pinyin } from 'pinyin-pro';

node 端:

javascript
const { pinyin } = require('pinyin-pro');

参数

pinyin(word, options) 接收两个参数

  • **word:**必填。String 类型,需要转化为拼音的中文
  • **options:**可选。Object 类型,用于配置各种输出形式,相关配置在后面有所介绍

基本用法

javascript
import { pinyin } from 'pinyin-pro'; // 若为node环境请用require形式引入

// 获取带音调拼音
pinyin('汉语拼音'); // 'hàn yǔ pīn yīn'
// 获取不带声调的拼音
pinyin('汉语拼音', { toneType: 'none' }); // 'han yu pin yin'
// 获取声调转换为数字后缀的拼音
pinyin('汉语拼音', { toneType: 'num' }); // 'han4 yu3 pin1 yin1'
// 获取声母
pinyin('汉语拼音', { pattern: 'initial' }); // 'h y p y'
// 获取带音调韵母
pinyin('汉语拼音', { pattern: 'final' }); // 'àn ǔ īn īn'
// 获取不带音调韵母
pinyin('汉语拼音', { pattern: 'final', toneType: 'none' }); // 'an u in in'
// 获取音调为数字的韵母
pinyin('汉语拼音', { pattern: 'final', toneType: 'num' }); // 'an4 u3 in1 in1'
// 获取音调
pinyin('汉语拼音', { pattern: 'num' }); // '4 3 1 1'

结果输出为数组格式

通过在 options 参数中加入type: 'array',可以以数组形式输出基本用法中的示例:

javascript
// 获取带音调拼音
pinyin('汉语拼音', { type: 'array' }); // ["hàn", "yǔ", "pīn", "yīn"]
// 获取不带声调的拼音
pinyin('汉语拼音', { toneType: 'none', type: 'array' }); // ["han", "yu", "pin", "yin"]
// 获取声调转换为数字后缀的拼音
pinyin('汉语拼音', { toneType: 'num', type: 'array' }); // ["han4", "yu3", "pin1", "yin1"]
// 获取声母
pinyin('汉语拼音', { pattern: 'initial', type: 'array' }); // ["h", "y", "p", "y"]
// 获取带音调韵母
pinyin('汉语拼音', { pattern: 'final', type: 'array' }); // ["àn", "ǔ", "īn", "īn"]
// 获取不带音调韵母
pinyin('汉语拼音', { pattern: 'final', toneType: 'none', type: 'array' }); // ["an", "u", "in", "in"]
// 获取音调
pinyin('汉语拼音', { pattern: 'num', type: 'array' }); // ["4", "3", "1", "1"]

获取单个字的多音

只有单字可以获取到多音模式, 词语、句子无效。同样可以通过配置 options 选项获取数组形式、韵母等格式

javascript
pinyin('好', { multiple: true }); // 'hǎo hào'
pinyin('好', { multiple: true, type: 'array' }); // ["hǎo", "hào"]

options 配置

参数 说明 类型 可选值 默认值
pattern 输出的结果的信息(拼音 / 声母 / 韵母 / 音调) string pinyin / initial / final / num pinyin
tone 音调输出形式(拼音符号 / 数字 / 不加音调) string symbol / num / none symbol
type 输出结果类型(字符串/数组) string string / array string
multiple 输出多音字全部拼音(仅在 word 为长度为 1 的汉字字符串时生效) boolean true / false false

交流与反馈

有问题或者功能需求支持欢迎提 issue


Packages Pinyin Pro Docs 3.0.X (`packages/pinyin-pro/docs/3.0.x.md`)







特色功能

  • 支持汉字、词语、句子多种格式输入获取
  • 获取拼音
  • 获取声母
  • 获取韵母
  • 获取拼音首字母
  • 获取音调
  • 获取多音字的多种拼音
  • 支持字符串和数组两种输出形式

版本更新

当前版本: 3.3.0 -> 3.3.1

  • 问题修复
    修复文本过长时堆栈溢出问题

点击查看 版本更新文档

安装

npm 安装

text
npm install pinyin-pro

yarn 安装

text
yarn add pinyin-pro

引入

浏览器 script 引入:

浏览器 script 引入:

html
<script src="https://cdn.jsdelivr.net/gh/zh-lx/pinyin-pro@latest/dist/pinyin-pro.js"></script>
<script>
  var { pinyin } = pinyinPro;
  pinyin('汉语拼音'); // 'hàn yǔ pīn yīn'
</script>

ESModule 引入:

javascript
import { pinyin } from 'pinyin-pro';
pinyin('汉语拼音'); // 'hàn yǔ pīn yīn'

commonjs 引入:

javascript
const { pinyin } = require('pinyin-pro');
pinyin('汉语拼音'); // 'hàn yǔ pīn yīn'

参数

pinyin(word, options) 接收两个参数

  • **word:**必填。String 类型,需要转化为拼音的中文
  • **options:**可选。Object 类型,用于配置各种输出形式,options 的键值配置如下:
参数 说明 类型 可选值 默认值
pattern 输出的结果的信息(拼音 / 声母 / 韵母 / 音调 / 首字母) string pinyin / initial / final / num / first pinyin
toneType 音调输出形式(拼音符号 / 数字 / 不加音调) string symbol / num / none symbol
type 输出结果类型(字符串/数组) string string / array string
multiple 输出多音字全部拼音(仅在 word 为长度为 1 的汉字字符串时生效) boolean true / false false

使用示例

获取拼音

js
import { pinyin } from 'pinyin-pro';

// 获取带音调拼音
pinyin('汉语拼音'); // 'hàn yǔ pīn yīn'
// 获取不带声调的拼音
pinyin('汉语拼音', { toneType: 'none' }); // 'han yu pin yin'
// 获取声调转换为数字后缀的拼音
pinyin('汉语拼音', { toneType: 'num' }); // 'han4 yu3 pin1 yin1'
// 获取数组形式带音调拼音
pinyin('汉语拼音', { type: 'array' }); // ["hàn", "yǔ", "pīn", "yīn"]
// 获取数组形式不带声调的拼音
pinyin('汉语拼音', { toneType: 'none', type: 'array' }); // ["han", "yu", "pin", "yin"]
// 获取数组形式声调转换为数字后缀的拼音
pinyin('汉语拼音', { toneType: 'num', type: 'array' }); // ["han4", "yu3", "pin1", "yin1"]

获取声母

js
import { pinyin } from 'pinyin-pro';

// 获取声母
pinyin('汉语拼音', { pattern: 'initial' }); // 'h y p y'
// 获取数组形式声母
pinyin('汉语拼音', { pattern: 'initial', type: 'array' }); // ["h", "y", "p", "y"]

获取韵母

js
import { pinyin } from 'pinyin-pro';

// 获取带音调韵母
pinyin('汉语拼音', { pattern: 'final' }); // 'àn ǔ īn īn'
// 获取不带音调韵母
pinyin('汉语拼音', { pattern: 'final', toneType: 'none' }); // 'an u in in'
// 获取音调为数字的韵母
pinyin('汉语拼音', { pattern: 'final', toneType: 'num' }); // 'an4 u3 in1 in1'
// 获取数组形式带音调韵母
pinyin('汉语拼音', { pattern: 'final', type: 'array' }); // ["àn", "ǔ", "īn", "īn"]
// 获取数组形式不带音调韵母
pinyin('汉语拼音', { pattern: 'final', toneType: 'none', type: 'array' }); // ["an", "u", "in", "in"]
// 获取数组形式音调为数字的韵母
pinyin('汉语拼音', { pattern: 'final', toneType: 'num', type: 'array' }); // ['an4', 'u3', 'in1', 'in1']

获取音调

js
import { pinyin } from 'pinyin-pro';

// 获取音调
pinyin('汉语拼音', { pattern: 'num' }); // '4 3 1 1'
// 获取数组形式音调
pinyin('汉语拼音', { pattern: 'num', type: 'array' }); // ["4", "3", "1", "1"]

获取拼音首字母

js
import { pinyin } from 'pinyin-pro';

// 获取拼音首字母
pinyin('赵钱孙李额', { pattern: 'first' }); // 'z q s l é'
// 获取不带音调拼音首字母
pinyin('赵钱孙李额', { pattern: 'first', toneType: 'none' }); // 'z q s l e'
// 获取数组形式拼音首字母
pinyin('赵钱孙李额', { pattern: 'first', type: 'array' }); // ['z', 'q', 's', 'l', 'é']
// 获取数组形式不带音调拼音首字母
pinyin('赵钱孙李额', { pattern: 'first', toneType: 'none', type: 'array' }); // ['z', 'q', 's', 'l', 'e']

获取单个字的多音

只有单字可以获取到多音模式, 词语、句子无效。同样可以通过配置 options 选项获取数组形式、韵母等格式

javascript
import { pinyin } from 'pinyin-pro';

// 获取多音
pinyin('好', { multiple: true }); // 'hǎo hào'
// 获取数组形式多音
pinyin('好', { multiple: true, type: 'array' }); // ["hǎo", "hào"]

贡献与反馈

使用遇到问题或者需要功能支持欢迎提 issue。

交流及参与贡献欢迎加微信:


Packages Pinyin Pro Docs 3.4.X (`packages/pinyin-pro/docs/3.4.x.md`)







特色功能

  • 支持汉字、词语、句子多种格式输入获取
  • 获取拼音
  • 获取声母
  • 获取韵母
  • 获取拼音首字母
  • 获取音调
  • 获取多音字的多种拼音
  • 支持人名姓氏模式
  • 支持自定义拼音
  • 支持字符串和数组两种输出形式

版本更新

当前版本: 3.3.1 -> 3.4.0

  • 新增功能
  • 问题修复
    修复文本过长时堆栈溢出问题
  • 字音校准
    • 褚: 'zhǔ' -> 'chǔ zhǔ'
    • 俞: 'yù' -> 'yú yù'
    • 臧: 'zàng' -> 'zāng'
    • 贲: 'bì' -> 'bēn bì'
    • 莘: 'xīn' -> 'shēn xīn'
    • 郦: 'zhí' -> 'lì zhí'

点击查看 版本更新文档

安装

npm 安装

text
npm install pinyin-pro

yarn 安装

text
yarn add pinyin-pro

引入

浏览器 script 引入:

html
<script src="https://cdn.jsdelivr.net/gh/zh-lx/pinyin-pro@latest/dist/pinyin-pro.js"></script>
<script>
  var { pinyin } = pinyinPro;
  pinyin('汉语拼音'); // 'hàn yǔ pīn yīn'
</script>

ESModule 引入:

javascript
import { pinyin } from 'pinyin-pro';
pinyin('汉语拼音'); // 'hàn yǔ pīn yīn'

commonjs 引入:

javascript
const { pinyin } = require('pinyin-pro');
pinyin('汉语拼音'); // 'hàn yǔ pīn yīn'

参数

pinyin(word, options) 接收两个参数

  • **word:**必填。String 类型,需要转化为拼音的中文
  • **options:**可选。Object 类型,用于配置各种输出形式,options 的键值配置如下:
参数 说明 类型 可选值 默认值
pattern 输出的结果的信息(拼音 / 声母 / 韵母 / 音调 / 首字母) string pinyin / initial / final / num / first pinyin
toneType 音调输出形式(拼音符号 / 数字 / 不加音调) string symbol / num / none symbol
type 输出结果类型(字符串/数组) string string / array string
multiple 输出多音字全部拼音(仅在 word 为长度为 1 的汉字字符串时生效) boolean true / false false
mode 拼音查找的模式(常规模式 / 姓氏模式) string normal / surname normal

使用示例

获取拼音

js
import { pinyin } from 'pinyin-pro';

// 获取带音调拼音
pinyin('汉语拼音'); // 'hàn yǔ pīn yīn'
// 获取不带声调的拼音
pinyin('汉语拼音', { toneType: 'none' }); // 'han yu pin yin'
// 获取声调转换为数字后缀的拼音
pinyin('汉语拼音', { toneType: 'num' }); // 'han4 yu3 pin1 yin1'
// 获取数组形式带音调拼音
pinyin('汉语拼音', { type: 'array' }); // ["hàn", "yǔ", "pīn", "yīn"]
// 获取数组形式不带声调的拼音
pinyin('汉语拼音', { toneType: 'none', type: 'array' }); // ["han", "yu", "pin", "yin"]
// 获取数组形式声调转换为数字后缀的拼音
pinyin('汉语拼音', { toneType: 'num', type: 'array' }); // ["han4", "yu3", "pin1", "yin1"]

获取声母

js
import { pinyin } from 'pinyin-pro';

// 获取声母
pinyin('汉语拼音', { pattern: 'initial' }); // 'h y p y'
// 获取数组形式声母
pinyin('汉语拼音', { pattern: 'initial', type: 'array' }); // ["h", "y", "p", "y"]

获取韵母

js
import { pinyin } from 'pinyin-pro';

// 获取带音调韵母
pinyin('汉语拼音', { pattern: 'final' }); // 'àn ǔ īn īn'
// 获取不带音调韵母
pinyin('汉语拼音', { pattern: 'final', toneType: 'none' }); // 'an u in in'
// 获取音调为数字的韵母
pinyin('汉语拼音', { pattern: 'final', toneType: 'num' }); // 'an4 u3 in1 in1'
// 获取数组形式带音调韵母
pinyin('汉语拼音', { pattern: 'final', type: 'array' }); // ["àn", "ǔ", "īn", "īn"]
// 获取数组形式不带音调韵母
pinyin('汉语拼音', { pattern: 'final', toneType: 'none', type: 'array' }); // ["an", "u", "in", "in"]
// 获取数组形式音调为数字的韵母
pinyin('汉语拼音', { pattern: 'final', toneType: 'num', type: 'array' }); // ['an4', 'u3', 'in1', 'in1']

获取音调

js
import { pinyin } from 'pinyin-pro';

// 获取音调
pinyin('汉语拼音', { pattern: 'num' }); // '4 3 1 1'
// 获取数组形式音调
pinyin('汉语拼音', { pattern: 'num', type: 'array' }); // ["4", "3", "1", "1"]

获取拼音首字母

js
import { pinyin } from 'pinyin-pro';

// 获取拼音首字母
pinyin('赵钱孙李额', { pattern: 'first' }); // 'z q s l é'
// 获取不带音调拼音首字母
pinyin('赵钱孙李额', { pattern: 'first', toneType: 'none' }); // 'z q s l e'
// 获取数组形式拼音首字母
pinyin('赵钱孙李额', { pattern: 'first', type: 'array' }); // ['z', 'q', 's', 'l', 'é']
// 获取数组形式不带音调拼音首字母
pinyin('赵钱孙李额', { pattern: 'first', toneType: 'none', type: 'array' }); // ['z', 'q', 's', 'l', 'e']

获取单个字的多音

只有单字可以获取到多音模式, 词语、句子无效。同样可以通过配置 options 选项获取数组形式、韵母等格式

javascript
import { pinyin } from 'pinyin-pro';

// 获取多音
pinyin('好', { multiple: true }); // 'hǎo hào'
// 获取数组形式多音
pinyin('好', { multiple: true, type: 'array' }); // ["hǎo", "hào"]

姓氏模式

通过设置 mode: 'surname' 开启姓氏模式后,匹配到百家姓中的姓氏优先输出姓氏拼音

javascript
import { pinyin } from 'pinyin-pro';

// 不开启姓氏模式
pinyin('我叫曾小贤'); // 'wǒ jiào céng xiǎo xián'

// 开启姓氏模式
pinyin('我叫曾小贤', { mode: 'surname' }); // 'wǒ jiào zēng xiǎo xián'

自定义拼音

包内部导出了 customPinyin 方法,支持用户自定义设置词句拼音,当中文中匹配用户自己定义的词句拼音时,优先使用用户自定义的词句拼音

javascript
import { pinyin, customPinyin } from 'pinyin-pro';

customPinyin({
  干一行行一行: 'gàn yī háng xíng yī háng',
});
pinyin('干一行行一行'); // 'gàn yī háng xíng yī háng'

贡献与反馈

参与开源贡献请参照 pinyin-pro 贡献

使用遇到问题或者需要功能支持欢迎提 issue。

交流及参与贡献欢迎加微信:


Packages Pinyin Pro Docs 3.5.X (`packages/pinyin-pro/docs/3.5.x.md`)







特色功能

版本更新

当前版本: 3.4.1 -> 3.5.0

点击查看 版本更新文档

安装

npm 安装

text
npm install pinyin-pro

yarn 安装

text
yarn add pinyin-pro

引入

浏览器 script 引入:

html
<script src="https://cdn.jsdelivr.net/gh/zh-lx/pinyin-pro@latest/dist/pinyin-pro.js"></script>
<script>
  var { pinyin } = pinyinPro;
  pinyin('汉语拼音'); // 'hàn yǔ pīn yīn'
</script>

ESModule 引入:

javascript
import { pinyin } from 'pinyin-pro';
pinyin('汉语拼音'); // 'hàn yǔ pīn yīn'

commonjs 引入:

javascript
const { pinyin } = require('pinyin-pro');
pinyin('汉语拼音'); // 'hàn yǔ pīn yīn'

参数

pinyin(word, options) 接收两个参数

  • **word:**必填。String 类型,需要转化为拼音的中文
  • **options:**可选。Object 类型,用于配置各种输出形式,options 的键值配置如下:
参数 说明 类型 可选值 默认值
pattern 输出的结果的信息(拼音 / 声母 / 韵母 / 音调 / 首字母) string pinyin / initial / final / num / first pinyin
toneType 音调输出形式(拼音符号 / 数字 / 不加音调) string symbol / num / none symbol
type 输出结果类型(字符串/数组) string string / array string
multiple 输出多音字全部拼音(仅在 word 为长度为 1 的汉字字符串时生效) boolean true / false false
mode 拼音查找的模式(常规模式 / 姓氏模式) string normal / surname normal

使用示例

获取拼音

js
import { pinyin } from 'pinyin-pro';

// 获取带音调拼音
pinyin('汉语拼音'); // 'hàn yǔ pīn yīn'
// 获取不带声调的拼音
pinyin('汉语拼音', { toneType: 'none' }); // 'han yu pin yin'
// 获取声调转换为数字后缀的拼音
pinyin('汉语拼音', { toneType: 'num' }); // 'han4 yu3 pin1 yin1'
// 获取数组形式带音调拼音
pinyin('汉语拼音', { type: 'array' }); // ["hàn", "yǔ", "pīn", "yīn"]
// 获取数组形式不带声调的拼音
pinyin('汉语拼音', { toneType: 'none', type: 'array' }); // ["han", "yu", "pin", "yin"]
// 获取数组形式声调转换为数字后缀的拼音
pinyin('汉语拼音', { toneType: 'num', type: 'array' }); // ["han4", "yu3", "pin1", "yin1"]

获取声母

js
import { pinyin } from 'pinyin-pro';

// 获取声母
pinyin('汉语拼音', { pattern: 'initial' }); // 'h y p y'
// 获取数组形式声母
pinyin('汉语拼音', { pattern: 'initial', type: 'array' }); // ["h", "y", "p", "y"]

获取韵母

js
import { pinyin } from 'pinyin-pro';

// 获取带音调韵母
pinyin('汉语拼音', { pattern: 'final' }); // 'àn ǔ īn īn'
// 获取不带音调韵母
pinyin('汉语拼音', { pattern: 'final', toneType: 'none' }); // 'an u in in'
// 获取音调为数字的韵母
pinyin('汉语拼音', { pattern: 'final', toneType: 'num' }); // 'an4 u3 in1 in1'
// 获取数组形式带音调韵母
pinyin('汉语拼音', { pattern: 'final', type: 'array' }); // ["àn", "ǔ", "īn", "īn"]
// 获取数组形式不带音调韵母
pinyin('汉语拼音', { pattern: 'final', toneType: 'none', type: 'array' }); // ["an", "u", "in", "in"]
// 获取数组形式音调为数字的韵母
pinyin('汉语拼音', { pattern: 'final', toneType: 'num', type: 'array' }); // ['an4', 'u3', 'in1', 'in1']

获取音调

js
import { pinyin } from 'pinyin-pro';

// 获取音调
pinyin('汉语拼音', { pattern: 'num' }); // '4 3 1 1'
// 获取数组形式音调
pinyin('汉语拼音', { pattern: 'num', type: 'array' }); // ["4", "3", "1", "1"]

获取拼音首字母

js
import { pinyin } from 'pinyin-pro';

// 获取拼音首字母
pinyin('赵钱孙李额', { pattern: 'first' }); // 'z q s l é'
// 获取不带音调拼音首字母
pinyin('赵钱孙李额', { pattern: 'first', toneType: 'none' }); // 'z q s l e'
// 获取数组形式拼音首字母
pinyin('赵钱孙李额', { pattern: 'first', type: 'array' }); // ['z', 'q', 's', 'l', 'é']
// 获取数组形式不带音调拼音首字母
pinyin('赵钱孙李额', { pattern: 'first', toneType: 'none', type: 'array' }); // ['z', 'q', 's', 'l', 'e']

获取单个字的多音

只有单字可以获取到多音模式, 词语、句子无效。同样可以通过配置 options 选项获取数组形式、韵母等格式

javascript
import { pinyin } from 'pinyin-pro';

// 获取多音
pinyin('好', { multiple: true }); // 'hǎo hào'
// 获取数组形式多音
pinyin('好', { multiple: true, type: 'array' }); // ["hǎo", "hào"]

姓氏模式

通过设置 mode: 'surname' 开启姓氏模式后,匹配到百家姓中的姓氏优先输出姓氏拼音

javascript
import { pinyin } from 'pinyin-pro';

// 不开启姓氏模式
pinyin('我叫曾小贤'); // 'wǒ jiào céng xiǎo xián'

// 开启姓氏模式
pinyin('我叫曾小贤', { mode: 'surname' }); // 'wǒ jiào zēng xiǎo xián'

自定义拼音

包内部导出了 customPinyin 方法,支持用户自定义设置词句拼音,当中文中匹配用户自己定义的词句拼音时,优先使用用户自定义的词句拼音

javascript
import { pinyin, customPinyin } from 'pinyin-pro';

customPinyin({
  干一行行一行: 'gàn yī háng xíng yī háng',
});
pinyin('干一行行一行'); // 'gàn yī háng xíng yī háng'

拼音匹配

包内含 match 方法,可以检测拼音和文本内容是否匹配,拼音支持缩写,且默认开启多音字所有读音匹配模式:

javascript
import { match } from 'pinyin-pro';

const matches1 = match('汉语拼音', 'hanyupinyin'); // [0, 1, 2, 3] 拼音和文本匹配,返回匹配上的文本下标
const matches2 = match('汉语拼音', 'hanpin'); // [0, 2] 拼音和文本匹配,返回匹配上的文本下标
const matches3 = match('汉语拼音', 'hyupy'); // [0, 1, 2, 3] 支持各种格式的拼音缩写匹配
const matches4 = match('汉语拼音', 'lsaf'); // null,未匹配成功返回 null
const matches5 = match('汉语拼音', 'hanyupinle'); // null,最后的 le 和音不匹配,匹配不成功,返回 null
const matches6 = match('会计', 'kuaiji'); // [0, 1],匹配成功,返回匹配上的文本下标
const matches7 = match('会计', 'huiji'); // [0, 1],多音字只要其中一个读音匹配上即算匹配成功

贡献与反馈

参与开源贡献请参照 pinyin-pro 贡献

使用遇到问题或者需要功能支持欢迎提 issue。

交流及参与贡献欢迎加微信:


Packages Pinyin Pro Docs 3.6.X (`packages/pinyin-pro/docs/3.6.x.md`)







特色功能

版本更新

当前版本: 3.5.0 -> 3.6.0

  • 新增功能
    • pinyin 方法新增 removeNonZh 参数,为 true 时移除非汉字的字符

点击查看 版本更新文档

安装

npm 安装

text
npm install pinyin-pro

yarn 安装

text
yarn add pinyin-pro

引入

浏览器 script 引入:

html
<script src="https://cdn.jsdelivr.net/gh/zh-lx/pinyin-pro@latest/dist/pinyin-pro.js"></script>
<script>
  var { pinyin } = pinyinPro;
  pinyin('汉语拼音'); // 'hàn yǔ pīn yīn'
</script>

ESModule 引入:

javascript
import { pinyin } from 'pinyin-pro';
pinyin('汉语拼音'); // 'hàn yǔ pīn yīn'

commonjs 引入:

javascript
const { pinyin } = require('pinyin-pro');
pinyin('汉语拼音'); // 'hàn yǔ pīn yīn'

参数

pinyin(word, options) 接收两个参数

  • **word:**必填。String 类型,需要转化为拼音的中文
  • **options:**可选。Object 类型,用于配置各种输出形式,options 的键值配置如下:
参数 说明 类型 可选值 默认值
pattern 输出的结果的信息(拼音 / 声母 / 韵母 / 音调 / 首字母) string pinyin / initial / final / num / first pinyin
toneType 音调输出形式(拼音符号 / 数字 / 不加音调) string symbol / num / none symbol
type 输出结果类型(字符串/数组) string string / array string
multiple 输出多音字全部拼音(仅在 word 为长度为 1 的汉字字符串时生效) boolean true / false false
mode 拼音查找的模式(常规模式 / 姓氏模式) string normal / surname normal
removeNonZh 是否输入字符串中将非汉字的字符过滤掉 boolean true / false false

使用示例

获取拼音

js
import { pinyin } from 'pinyin-pro';

// 获取带音调拼音
pinyin('汉语拼音'); // 'hàn yǔ pīn yīn'
// 获取不带声调的拼音
pinyin('汉语拼音', { toneType: 'none' }); // 'han yu pin yin'
// 获取声调转换为数字后缀的拼音
pinyin('汉语拼音', { toneType: 'num' }); // 'han4 yu3 pin1 yin1'
// 获取数组形式带音调拼音
pinyin('汉语拼音', { type: 'array' }); // ["hàn", "yǔ", "pīn", "yīn"]
// 获取数组形式不带声调的拼音
pinyin('汉语拼音', { toneType: 'none', type: 'array' }); // ["han", "yu", "pin", "yin"]
// 获取数组形式声调转换为数字后缀的拼音
pinyin('汉语拼音', { toneType: 'num', type: 'array' }); // ["han4", "yu3", "pin1", "yin1"]

获取声母

js
import { pinyin } from 'pinyin-pro';

// 获取声母
pinyin('汉语拼音', { pattern: 'initial' }); // 'h y p y'
// 获取数组形式声母
pinyin('汉语拼音', { pattern: 'initial', type: 'array' }); // ["h", "y", "p", "y"]

获取韵母

js
import { pinyin } from 'pinyin-pro';

// 获取带音调韵母
pinyin('汉语拼音', { pattern: 'final' }); // 'àn ǔ īn īn'
// 获取不带音调韵母
pinyin('汉语拼音', { pattern: 'final', toneType: 'none' }); // 'an u in in'
// 获取音调为数字的韵母
pinyin('汉语拼音', { pattern: 'final', toneType: 'num' }); // 'an4 u3 in1 in1'
// 获取数组形式带音调韵母
pinyin('汉语拼音', { pattern: 'final', type: 'array' }); // ["àn", "ǔ", "īn", "īn"]
// 获取数组形式不带音调韵母
pinyin('汉语拼音', { pattern: 'final', toneType: 'none', type: 'array' }); // ["an", "u", "in", "in"]
// 获取数组形式音调为数字的韵母
pinyin('汉语拼音', { pattern: 'final', toneType: 'num', type: 'array' }); // ['an4', 'u3', 'in1', 'in1']

获取音调

js
import { pinyin } from 'pinyin-pro';

// 获取音调
pinyin('汉语拼音', { pattern: 'num' }); // '4 3 1 1'
// 获取数组形式音调
pinyin('汉语拼音', { pattern: 'num', type: 'array' }); // ["4", "3", "1", "1"]

获取拼音首字母

js
import { pinyin } from 'pinyin-pro';

// 获取拼音首字母
pinyin('赵钱孙李额', { pattern: 'first' }); // 'z q s l é'
// 获取不带音调拼音首字母
pinyin('赵钱孙李额', { pattern: 'first', toneType: 'none' }); // 'z q s l e'
// 获取数组形式拼音首字母
pinyin('赵钱孙李额', { pattern: 'first', type: 'array' }); // ['z', 'q', 's', 'l', 'é']
// 获取数组形式不带音调拼音首字母
pinyin('赵钱孙李额', { pattern: 'first', toneType: 'none', type: 'array' }); // ['z', 'q', 's', 'l', 'e']

获取单个字的多音

只有单字可以获取到多音模式, 词语、句子无效。同样可以通过配置 options 选项获取数组形式、韵母等格式

javascript
import { pinyin } from 'pinyin-pro';

// 获取多音
pinyin('好', { multiple: true }); // 'hǎo hào'
// 获取数组形式多音
pinyin('好', { multiple: true, type: 'array' }); // ["hǎo", "hào"]

姓氏模式

通过设置 mode: 'surname' 开启姓氏模式后,匹配到百家姓中的姓氏优先输出姓氏拼音

javascript
import { pinyin } from 'pinyin-pro';

// 不开启姓氏模式
pinyin('我叫曾小贤'); // 'wǒ jiào céng xiǎo xián'

// 开启姓氏模式
pinyin('我叫曾小贤', { mode: 'surname' }); // 'wǒ jiào zēng xiǎo xián'

过滤非汉字字符

通过设置 removeNonZh: true ,可以过滤输入字符串中的非汉字字符

javascript
import { pinyin } from 'pinyin-pro';

// 不开启过滤
pinyin('汉sa语2拼音'); // 'hàn s a yǔ 2 pīn yīn'

// 开启过滤
pinyin('汉sa语2拼音', { removeNonZh: true }); // 'hàn yǔ pīn yīn'

自定义拼音

包内部导出了 customPinyin 方法,支持用户自定义设置词句拼音,当中文中匹配用户自己定义的词句拼音时,优先使用用户自定义的词句拼音

javascript
import { pinyin, customPinyin } from 'pinyin-pro';

customPinyin({
  干一行行一行: 'gàn yī háng xíng yī háng',
});
pinyin('干一行行一行'); // 'gàn yī háng xíng yī háng'

拼音匹配

包内含 match 方法,可以检测拼音和文本内容是否匹配,拼音支持缩写,且默认开启多音字所有读音匹配模式:

javascript
import { match } from 'pinyin-pro';

const matches1 = match('汉语拼音', 'hanyupinyin'); // [0, 1, 2, 3] 拼音和文本匹配,返回匹配上的文本下标
const matches2 = match('汉语拼音', 'hanpin'); // [0, 2] 拼音和文本匹配,返回匹配上的文本下标
const matches3 = match('汉语拼音', 'hyupy'); // [0, 1, 2, 3] 支持各种格式的拼音缩写匹配
const matches4 = match('汉语拼音', 'lsaf'); // null,未匹配成功返回 null
const matches5 = match('汉语拼音', 'hanyupinle'); // null,最后的 le 和音不匹配,匹配不成功,返回 null
const matches6 = match('会计', 'kuaiji'); // [0, 1],匹配成功,返回匹配上的文本下标
const matches7 = match('会计', 'huiji'); // [0, 1],多音字只要其中一个读音匹配上即算匹配成功

贡献与反馈

参与开源贡献请参照 pinyin-pro 贡献

使用遇到问题或者需要功能支持欢迎提 issue。

交流及参与贡献欢迎加微信:


Packages Pinyin Pro Docs 3.7.X (`packages/pinyin-pro/docs/3.7.x.md`)







特色功能

版本更新

当前版本: 3.7.0 -> 3.7.1

  • 修复问题
    • 修复 “嗯” 在 toneType: 'none' 下拼音转换错误的问题

点击查看 版本更新文档

安装

npm 安装

text
npm install pinyin-pro

yarn 安装

text
yarn add pinyin-pro

引入

浏览器 script 引入:

html
<script src="https://cdn.jsdelivr.net/gh/zh-lx/pinyin-pro@latest/dist/pinyin-pro.js"></script>
<script>
  var { pinyin } = pinyinPro;
  pinyin('汉语拼音'); // 'hàn yǔ pīn yīn'
</script>

commonjs 浏览器引入:

javascript
import { pinyin } from 'pinyin-pro';
pinyin('汉语拼音'); // 'hàn yǔ pīn yīn'

commonjs node 引入:

javascript
const { pinyin } = require('pinyin-pro');
pinyin('汉语拼音'); // 'hàn yǔ pīn yīn'

esm 引入:

javascript
import('pinyin-pro').then((exports) => {
  exports.pinyin('汉语拼音'); // 'hàn yǔ pīn yīn'
});

参数

pinyin(word, options) 接收两个参数

  • **word:**必填。String 类型,需要转化为拼音的中文
  • **options:**可选。Object 类型,用于配置各种输出形式,options 的键值配置如下:
参数 说明 类型 可选值 默认值
pattern 输出的结果的信息(拼音 / 声母 / 韵母 / 音调 / 首字母) string pinyin / initial / final / num / first pinyin
toneType 音调输出形式(拼音符号 / 数字 / 不加音调) string symbol / num / none symbol
type 输出结果类型(字符串/数组) string string / array string
multiple 输出多音字全部拼音(仅在 word 为长度为 1 的汉字字符串时生效) boolean true / false false
mode 拼音查找的模式(常规模式 / 姓氏模式) string normal / surname normal
removeNonZh 是否输入字符串中将非汉字的字符过滤掉 boolean true / false false

使用示例

获取拼音

js
import { pinyin } from 'pinyin-pro';

// 获取带音调拼音
pinyin('汉语拼音'); // 'hàn yǔ pīn yīn'
// 获取不带声调的拼音
pinyin('汉语拼音', { toneType: 'none' }); // 'han yu pin yin'
// 获取声调转换为数字后缀的拼音
pinyin('汉语拼音', { toneType: 'num' }); // 'han4 yu3 pin1 yin1'
// 获取数组形式带音调拼音
pinyin('汉语拼音', { type: 'array' }); // ["hàn", "yǔ", "pīn", "yīn"]
// 获取数组形式不带声调的拼音
pinyin('汉语拼音', { toneType: 'none', type: 'array' }); // ["han", "yu", "pin", "yin"]
// 获取数组形式声调转换为数字后缀的拼音
pinyin('汉语拼音', { toneType: 'num', type: 'array' }); // ["han4", "yu3", "pin1", "yin1"]

获取声母

js
import { pinyin } from 'pinyin-pro';

// 获取声母
pinyin('汉语拼音', { pattern: 'initial' }); // 'h y p y'
// 获取数组形式声母
pinyin('汉语拼音', { pattern: 'initial', type: 'array' }); // ["h", "y", "p", "y"]

获取韵母

js
import { pinyin } from 'pinyin-pro';

// 获取带音调韵母
pinyin('汉语拼音', { pattern: 'final' }); // 'àn ǔ īn īn'
// 获取不带音调韵母
pinyin('汉语拼音', { pattern: 'final', toneType: 'none' }); // 'an u in in'
// 获取音调为数字的韵母
pinyin('汉语拼音', { pattern: 'final', toneType: 'num' }); // 'an4 u3 in1 in1'
// 获取数组形式带音调韵母
pinyin('汉语拼音', { pattern: 'final', type: 'array' }); // ["àn", "ǔ", "īn", "īn"]
// 获取数组形式不带音调韵母
pinyin('汉语拼音', { pattern: 'final', toneType: 'none', type: 'array' }); // ["an", "u", "in", "in"]
// 获取数组形式音调为数字的韵母
pinyin('汉语拼音', { pattern: 'final', toneType: 'num', type: 'array' }); // ['an4', 'u3', 'in1', 'in1']

获取音调

js
import { pinyin } from 'pinyin-pro';

// 获取音调
pinyin('汉语拼音', { pattern: 'num' }); // '4 3 1 1'
// 获取数组形式音调
pinyin('汉语拼音', { pattern: 'num', type: 'array' }); // ["4", "3", "1", "1"]

获取拼音首字母

js
import { pinyin } from 'pinyin-pro';

// 获取拼音首字母
pinyin('赵钱孙李额', { pattern: 'first' }); // 'z q s l é'
// 获取不带音调拼音首字母
pinyin('赵钱孙李额', { pattern: 'first', toneType: 'none' }); // 'z q s l e'
// 获取数组形式拼音首字母
pinyin('赵钱孙李额', { pattern: 'first', type: 'array' }); // ['z', 'q', 's', 'l', 'é']
// 获取数组形式不带音调拼音首字母
pinyin('赵钱孙李额', { pattern: 'first', toneType: 'none', type: 'array' }); // ['z', 'q', 's', 'l', 'e']

获取单个字的多音

只有单字可以获取到多音模式, 词语、句子无效。同样可以通过配置 options 选项获取数组形式、韵母等格式

javascript
import { pinyin } from 'pinyin-pro';

// 获取多音
pinyin('好', { multiple: true }); // 'hǎo hào'
// 获取数组形式多音
pinyin('好', { multiple: true, type: 'array' }); // ["hǎo", "hào"]

姓氏模式

通过设置 mode: 'surname' 开启姓氏模式后,匹配到百家姓中的姓氏优先输出姓氏拼音

javascript
import { pinyin } from 'pinyin-pro';

// 不开启姓氏模式
pinyin('我叫曾小贤'); // 'wǒ jiào céng xiǎo xián'

// 开启姓氏模式
pinyin('我叫曾小贤', { mode: 'surname' }); // 'wǒ jiào zēng xiǎo xián'

过滤非汉字字符

通过设置 removeNonZh: true ,可以过滤输入字符串中的非汉字字符

javascript
import { pinyin } from 'pinyin-pro';

// 不开启过滤
pinyin('汉sa语2拼音'); // 'hàn s a yǔ 2 pīn yīn'

// 开启过滤
pinyin('汉sa语2拼音', { removeNonZh: true }); // 'hàn yǔ pīn yīn'

自定义拼音

包内部导出了 customPinyin 方法,支持用户自定义设置词句拼音,当中文中匹配用户自己定义的词句拼音时,优先使用用户自定义的词句拼音

javascript
import { pinyin, customPinyin } from 'pinyin-pro';

customPinyin({
  干一行行一行: 'gàn yī háng xíng yī háng',
});
pinyin('干一行行一行'); // 'gàn yī háng xíng yī háng'

拼音匹配

包内含 match 方法,可以检测拼音和文本内容是否匹配,拼音支持缩写,且默认开启多音字所有读音匹配模式:

javascript
import { match } from 'pinyin-pro';

const matches1 = match('汉语拼音', 'hanyupinyin'); // [0, 1, 2, 3] 拼音和文本匹配,返回匹配上的文本下标
const matches2 = match('汉语拼音', 'hanpin'); // [0, 2] 拼音和文本匹配,返回匹配上的文本下标
const matches3 = match('汉语拼音', 'hyupy'); // [0, 1, 2, 3] 支持各种格式的拼音缩写匹配
const matches4 = match('汉语拼音', 'lsaf'); // null,未匹配成功返回 null
const matches5 = match('汉语拼音', 'hanyupinle'); // null,最后的 le 和音不匹配,匹配不成功,返回 null
const matches6 = match('会计', 'kuaiji'); // [0, 1],匹配成功,返回匹配上的文本下标
const matches7 = match('会计', 'huiji'); // [0, 1],多音字只要其中一个读音匹配上即算匹配成功

贡献与反馈

参与开源贡献请参照 pinyin-pro 贡献

使用遇到问题或者需要功能支持欢迎提 issue。

交流及参与贡献欢迎加微信:


Packages Pinyin Pro Docs 3.8.X (`packages/pinyin-pro/docs/3.8.x.md`)







特色功能

版本更新

当前版本: 3.7.2 -> 3.8.0

  • 新增功能
    • 增加 nonZh 可选参数,用于配置非中文字符串的输出规则

点击查看 版本更新文档

安装

npm 安装

text
npm install pinyin-pro

yarn 安装

text
yarn add pinyin-pro

引入

浏览器 script 引入:

html
<script src="https://cdn.jsdelivr.net/gh/zh-lx/pinyin-pro@latest/dist/pinyin-pro.js"></script>
<script>
  var { pinyin } = pinyinPro;
  pinyin('汉语拼音'); // 'hàn yǔ pīn yīn'
</script>

commonjs 浏览器引入:

javascript
import { pinyin } from 'pinyin-pro';
pinyin('汉语拼音'); // 'hàn yǔ pīn yīn'

commonjs node 引入:

javascript
const { pinyin } = require('pinyin-pro');
pinyin('汉语拼音'); // 'hàn yǔ pīn yīn'

esm 引入:

javascript
import('pinyin-pro').then((exports) => {
  exports.pinyin('汉语拼音'); // 'hàn yǔ pīn yīn'
});

参数

pinyin(word, options) 接收两个参数

  • **word:**必填。String 类型,需要转化为拼音的中文
  • **options:**可选。Object 类型,用于配置各种输出形式,options 的键值配置如下:
参数 说明 类型 可选值 默认值
pattern 输出的结果的信息(拼音 / 声母 / 韵母 / 音调 / 首字母) string pinyin / initial / final / num / first pinyin
toneType 音调输出形式(拼音符号 / 数字 / 不加音调) string symbol / num / none symbol
type 输出结果类型(字符串/数组) string string / array string
multiple 输出多音字全部拼音(仅在 word 为长度为 1 的汉字字符串时生效) boolean true / false false
mode 拼音查找的模式(常规模式 / 姓氏模式) string normal / surname normal
removeNonZh 是否输入字符串中将非汉字的字符过滤掉 boolean true / false false
nonZh 定义非汉字字符的输出形式 string spaced / consecutive / removed spaced

使用示例

获取拼音

js
import { pinyin } from 'pinyin-pro';

// 获取带音调拼音
pinyin('汉语拼音'); // 'hàn yǔ pīn yīn'
// 获取不带声调的拼音
pinyin('汉语拼音', { toneType: 'none' }); // 'han yu pin yin'
// 获取声调转换为数字后缀的拼音
pinyin('汉语拼音', { toneType: 'num' }); // 'han4 yu3 pin1 yin1'
// 获取数组形式带音调拼音
pinyin('汉语拼音', { type: 'array' }); // ["hàn", "yǔ", "pīn", "yīn"]
// 获取数组形式不带声调的拼音
pinyin('汉语拼音', { toneType: 'none', type: 'array' }); // ["han", "yu", "pin", "yin"]
// 获取数组形式声调转换为数字后缀的拼音
pinyin('汉语拼音', { toneType: 'num', type: 'array' }); // ["han4", "yu3", "pin1", "yin1"]

获取声母

js
import { pinyin } from 'pinyin-pro';

// 获取声母
pinyin('汉语拼音', { pattern: 'initial' }); // 'h y p y'
// 获取数组形式声母
pinyin('汉语拼音', { pattern: 'initial', type: 'array' }); // ["h", "y", "p", "y"]

获取韵母

js
import { pinyin } from 'pinyin-pro';

// 获取带音调韵母
pinyin('汉语拼音', { pattern: 'final' }); // 'àn ǔ īn īn'
// 获取不带音调韵母
pinyin('汉语拼音', { pattern: 'final', toneType: 'none' }); // 'an u in in'
// 获取音调为数字的韵母
pinyin('汉语拼音', { pattern: 'final', toneType: 'num' }); // 'an4 u3 in1 in1'
// 获取数组形式带音调韵母
pinyin('汉语拼音', { pattern: 'final', type: 'array' }); // ["àn", "ǔ", "īn", "īn"]
// 获取数组形式不带音调韵母
pinyin('汉语拼音', { pattern: 'final', toneType: 'none', type: 'array' }); // ["an", "u", "in", "in"]
// 获取数组形式音调为数字的韵母
pinyin('汉语拼音', { pattern: 'final', toneType: 'num', type: 'array' }); // ['an4', 'u3', 'in1', 'in1']

获取音调

js
import { pinyin } from 'pinyin-pro';

// 获取音调
pinyin('汉语拼音', { pattern: 'num' }); // '4 3 1 1'
// 获取数组形式音调
pinyin('汉语拼音', { pattern: 'num', type: 'array' }); // ["4", "3", "1", "1"]

获取拼音首字母

js
import { pinyin } from 'pinyin-pro';

// 获取拼音首字母
pinyin('赵钱孙李额', { pattern: 'first' }); // 'z q s l é'
// 获取不带音调拼音首字母
pinyin('赵钱孙李额', { pattern: 'first', toneType: 'none' }); // 'z q s l e'
// 获取数组形式拼音首字母
pinyin('赵钱孙李额', { pattern: 'first', type: 'array' }); // ['z', 'q', 's', 'l', 'é']
// 获取数组形式不带音调拼音首字母
pinyin('赵钱孙李额', { pattern: 'first', toneType: 'none', type: 'array' }); // ['z', 'q', 's', 'l', 'e']

获取单个字的多音

只有单字可以获取到多音模式, 词语、句子无效。同样可以通过配置 options 选项获取数组形式、韵母等格式

javascript
import { pinyin } from 'pinyin-pro';

// 获取多音
pinyin('好', { multiple: true }); // 'hǎo hào'
// 获取数组形式多音
pinyin('好', { multiple: true, type: 'array' }); // ["hǎo", "hào"]

姓氏模式

通过设置 mode: 'surname' 开启姓氏模式后,匹配到百家姓中的姓氏优先输出姓氏拼音

javascript
import { pinyin } from 'pinyin-pro';

// 不开启姓氏模式
pinyin('我叫曾小贤'); // 'wǒ jiào céng xiǎo xián'

// 开启姓氏模式
pinyin('我叫曾小贤', { mode: 'surname' }); // 'wǒ jiào zēng xiǎo xián'

过滤非汉字字符

通过设置 removeNonZh: true ,可以过滤输入字符串中的非汉字字符
此参数已不推荐使用,建议使用 nonZh: removed 代替

javascript
import { pinyin } from 'pinyin-pro';

// 不开启过滤
pinyin('汉sa语2拼音'); // 'hàn s a yǔ 2 pīn yīn'

// 开启过滤
pinyin('汉sa语2拼音', { removeNonZh: true }); // 'hàn yǔ pīn yīn'

定义非汉字字符输出形式

通过设置 nonZh ,可以设置非汉字字符的不同输出形式

javascript
import { pinyin } from 'pinyin-pro';

pinyin('我very喜欢你'); // 'wǒ v e r y xǐ huān nǐ' 默认以空格间隔输出

pinyin('我very喜欢你', { nonZh: 'spaced' }); // 'wǒ v e r y xǐ huān nǐ' 以空格间隔输出

pinyin('我very喜欢你', { nonZh: 'consecutive' }); // 'wǒ very xǐ huān nǐ' 紧凑输出

pinyin('我very喜欢你', { nonZh: 'removed' }); // 'wǒ xǐ huān nǐ' 移除非汉字字符

自定义拼音

包内部导出了 customPinyin 方法,支持用户自定义设置词句拼音,当中文中匹配用户自己定义的词句拼音时,优先使用用户自定义的词句拼音

javascript
import { pinyin, customPinyin } from 'pinyin-pro';

customPinyin({
  干一行行一行: 'gàn yī háng xíng yī háng',
});
pinyin('干一行行一行'); // 'gàn yī háng xíng yī háng'

拼音匹配

包内含 match 方法,可以检测拼音和文本内容是否匹配,拼音支持缩写,且默认开启多音字所有读音匹配模式:

javascript
import { match } from 'pinyin-pro';

const matches1 = match('汉语拼音', 'hanyupinyin'); // [0, 1, 2, 3] 拼音和文本匹配,返回匹配上的文本下标
const matches2 = match('汉语拼音', 'hanpin'); // [0, 2] 拼音和文本匹配,返回匹配上的文本下标
const matches3 = match('汉语拼音', 'hyupy'); // [0, 1, 2, 3] 支持各种格式的拼音缩写匹配
const matches4 = match('汉语拼音', 'lsaf'); // null,未匹配成功返回 null
const matches5 = match('汉语拼音', 'hanyupinle'); // null,最后的 le 和音不匹配,匹配不成功,返回 null
const matches6 = match('会计', 'kuaiji'); // [0, 1],匹配成功,返回匹配上的文本下标
const matches7 = match('会计', 'huiji'); // [0, 1],多音字只要其中一个读音匹配上即算匹配成功

贡献与反馈

参与开源贡献请参照 pinyin-pro 贡献

使用遇到问题或者需要功能支持欢迎提 issue。

交流及参与贡献欢迎加微信:


Packages Pinyin Pro Docs 3.9.X (`packages/pinyin-pro/docs/3.9.x.md`)







特色功能

版本更新

当前版本: 3.8.3 -> 3.9.0

  • 新增功能:
    支持增加 v: true 可选项将拼音 ü 替换为 v

点击查看 版本更新文档

安装

npm 安装

text
npm install pinyin-pro

yarn 安装

text
yarn add pinyin-pro

引入

浏览器 script 引入:

html
<script src="https://cdn.jsdelivr.net/gh/zh-lx/pinyin-pro@latest/dist/pinyin-pro.js"></script>
<script>
  var { pinyin } = pinyinPro;
  pinyin('汉语拼音'); // 'hàn yǔ pīn yīn'
</script>

commonjs 浏览器引入:

javascript
import { pinyin } from 'pinyin-pro';
pinyin('汉语拼音'); // 'hàn yǔ pīn yīn'

commonjs node 引入:

javascript
const { pinyin } = require('pinyin-pro');
pinyin('汉语拼音'); // 'hàn yǔ pīn yīn'

esm 引入:

javascript
import('pinyin-pro').then((exports) => {
  exports.pinyin('汉语拼音'); // 'hàn yǔ pīn yīn'
});

参数

pinyin(word, options) 接收两个参数

  • **word:**必填。String 类型,需要转化为拼音的中文
  • **options:**可选。Object 类型,用于配置各种输出形式,options 的键值配置如下:
参数 说明 类型 可选值 默认值
pattern 输出的结果的信息(拼音 / 声母 / 韵母 / 音调 / 首字母) string pinyin / initial / final / num / first pinyin
toneType 音调输出形式(拼音符号 / 数字 / 不加音调) string symbol / num / none symbol
type 输出结果类型(字符串/数组) string string / array string
multiple 输出多音字全部拼音(仅在 word 为长度为 1 的汉字字符串时生效) boolean true / false false
mode 拼音查找的模式(常规模式 / 姓氏模式) string normal / surname normal
removeNonZh 是否输入字符串中将非汉字的字符过滤掉 boolean true / false false
nonZh 定义非汉字字符的输出形式 string spaced / consecutive / removed spaced
v 是否将拼音 ü 替换为 v boolean true / false false

使用示例

获取拼音

js
import { pinyin } from 'pinyin-pro';

// 获取带音调拼音
pinyin('汉语拼音'); // 'hàn yǔ pīn yīn'
// 获取不带声调的拼音
pinyin('汉语拼音', { toneType: 'none' }); // 'han yu pin yin'
// 获取声调转换为数字后缀的拼音
pinyin('汉语拼音', { toneType: 'num' }); // 'han4 yu3 pin1 yin1'
// 获取数组形式带音调拼音
pinyin('汉语拼音', { type: 'array' }); // ["hàn", "yǔ", "pīn", "yīn"]
// 获取数组形式不带声调的拼音
pinyin('汉语拼音', { toneType: 'none', type: 'array' }); // ["han", "yu", "pin", "yin"]
// 获取数组形式声调转换为数字后缀的拼音
pinyin('汉语拼音', { toneType: 'num', type: 'array' }); // ["han4", "yu3", "pin1", "yin1"]

获取声母

js
import { pinyin } from 'pinyin-pro';

// 获取声母
pinyin('汉语拼音', { pattern: 'initial' }); // 'h y p y'
// 获取数组形式声母
pinyin('汉语拼音', { pattern: 'initial', type: 'array' }); // ["h", "y", "p", "y"]

获取韵母

js
import { pinyin } from 'pinyin-pro';

// 获取带音调韵母
pinyin('汉语拼音', { pattern: 'final' }); // 'àn ǔ īn īn'
// 获取不带音调韵母
pinyin('汉语拼音', { pattern: 'final', toneType: 'none' }); // 'an u in in'
// 获取音调为数字的韵母
pinyin('汉语拼音', { pattern: 'final', toneType: 'num' }); // 'an4 u3 in1 in1'
// 获取数组形式带音调韵母
pinyin('汉语拼音', { pattern: 'final', type: 'array' }); // ["àn", "ǔ", "īn", "īn"]
// 获取数组形式不带音调韵母
pinyin('汉语拼音', { pattern: 'final', toneType: 'none', type: 'array' }); // ["an", "u", "in", "in"]
// 获取数组形式音调为数字的韵母
pinyin('汉语拼音', { pattern: 'final', toneType: 'num', type: 'array' }); // ['an4', 'u3', 'in1', 'in1']

获取音调

js
import { pinyin } from 'pinyin-pro';

// 获取音调
pinyin('汉语拼音', { pattern: 'num' }); // '4 3 1 1'
// 获取数组形式音调
pinyin('汉语拼音', { pattern: 'num', type: 'array' }); // ["4", "3", "1", "1"]

获取拼音首字母

js
import { pinyin } from 'pinyin-pro';

// 获取拼音首字母
pinyin('赵钱孙李额', { pattern: 'first' }); // 'z q s l é'
// 获取不带音调拼音首字母
pinyin('赵钱孙李额', { pattern: 'first', toneType: 'none' }); // 'z q s l e'
// 获取数组形式拼音首字母
pinyin('赵钱孙李额', { pattern: 'first', type: 'array' }); // ['z', 'q', 's', 'l', 'é']
// 获取数组形式不带音调拼音首字母
pinyin('赵钱孙李额', { pattern: 'first', toneType: 'none', type: 'array' }); // ['z', 'q', 's', 'l', 'e']

获取单个字的多音

只有单字可以获取到多音模式, 词语、句子无效。同样可以通过配置 options 选项获取数组形式、韵母等格式

javascript
import { pinyin } from 'pinyin-pro';

// 获取多音
pinyin('好', { multiple: true }); // 'hǎo hào'
// 获取数组形式多音
pinyin('好', { multiple: true, type: 'array' }); // ["hǎo", "hào"]

姓氏模式

通过设置 mode: 'surname' 开启姓氏模式后,匹配到百家姓中的姓氏优先输出姓氏拼音

javascript
import { pinyin } from 'pinyin-pro';

// 不开启姓氏模式
pinyin('我叫曾小贤'); // 'wǒ jiào céng xiǎo xián'

// 开启姓氏模式
pinyin('我叫曾小贤', { mode: 'surname' }); // 'wǒ jiào zēng xiǎo xián'

过滤非汉字字符

通过设置 removeNonZh: true ,可以过滤输入字符串中的非汉字字符
此参数已不推荐使用,建议使用 nonZh: removed 代替

javascript
import { pinyin } from 'pinyin-pro';

// 不开启过滤
pinyin('汉sa语2拼音'); // 'hàn s a yǔ 2 pīn yīn'

// 开启过滤
pinyin('汉sa语2拼音', { removeNonZh: true }); // 'hàn yǔ pīn yīn'

定义非汉字字符输出形式

通过设置 nonZh ,可以设置非汉字字符的不同输出形式

javascript
import { pinyin } from 'pinyin-pro';

pinyin('我very喜欢你'); // 'wǒ v e r y xǐ huān nǐ' 默认以空格间隔输出

pinyin('我very喜欢你', { nonZh: 'spaced' }); // 'wǒ v e r y xǐ huān nǐ' 以空格间隔输出

pinyin('我very喜欢你', { nonZh: 'consecutive' }); // 'wǒ very xǐ huān nǐ' 紧凑输出

pinyin('我very喜欢你', { nonZh: 'removed' }); // 'wǒ xǐ huān nǐ' 移除非汉字字符

自定义拼音

包内部导出了 customPinyin 方法,支持用户自定义设置词句拼音,当中文中匹配用户自己定义的词句拼音时,优先使用用户自定义的词句拼音

javascript
import { pinyin, customPinyin } from 'pinyin-pro';

customPinyin({
  干一行行一行: 'gàn yī háng xíng yī háng',
});
pinyin('干一行行一行'); // 'gàn yī háng xíng yī háng'

拼音匹配

包内含 match 方法,可以检测拼音和文本内容是否匹配,拼音支持缩写,且默认开启多音字所有读音匹配模式:

javascript
import { match } from 'pinyin-pro';

const matches1 = match('汉语拼音', 'hanyupinyin'); // [0, 1, 2, 3] 拼音和文本匹配,返回匹配上的文本下标
const matches2 = match('汉语拼音', 'hanpin'); // [0, 2] 拼音和文本匹配,返回匹配上的文本下标
const matches3 = match('汉语拼音', 'hyupy'); // [0, 1, 2, 3] 支持各种格式的拼音缩写匹配
const matches4 = match('汉语拼音', 'lsaf'); // null,未匹配成功返回 null
const matches5 = match('汉语拼音', 'hanyupinle'); // null,最后的 le 和音不匹配,匹配不成功,返回 null
const matches6 = match('会计', 'kuaiji'); // [0, 1],匹配成功,返回匹配上的文本下标
const matches7 = match('会计', 'huiji'); // [0, 1],多音字只要其中一个读音匹配上即算匹配成功

将拼音 ǚ 替换为 v

设置可选配置项 v: true 之后,转换结果中的 ü 将会被替换为 v (带音调的 ü 不会被转换):
:

javascript
import { pinyin } from 'pinyin-pro';

const result1 = pinyin('吕布', { toneType: 'none' }); // lü bu
const result2 = pinyin('吕布', { toneType: 'none', v: true }); // lv bu
const result3 = pinyin('吕布', { v: true }); // lǚ bù

贡献与反馈

参与开源贡献请参照 pinyin-pro 贡献

使用遇到问题或者需要功能支持欢迎提 issue。

交流及参与贡献欢迎加微信:


Packages Pinyin Pro Docs Contribute (`packages/pinyin-pro/docs/contribute.md`)

流程
欢迎贡献源码,我们会及时审核、合并。

  • fork 源码,下载到本地,并在仓库根目录运行 pnpm install
  • 修改代码后,运行 yarn test 自测跑通所有测试用例
  • 提交代码到你的 github 仓库
  • 提交 Pull Request ,合并到 master 分支

Packages Docs En Docs Guide Api Size (`packages/docs/en/docs/guide/api-size.md`)

API Size

The following data is automatically generated by pnpm size. ESM API sizes are measured after independent bundling and Tree Shaking; UMD does not support API-level Tree Shaking, so its full artifact size is shown. Gzip sizes are shown in parentheses.

API ESM UMD
pinyin 307.03 KB (gzip 134.83 KB) 317.47 KB (gzip 138.33 KB)
segment 305.79 KB (gzip 134.04 KB)
match 185.67 KB (gzip 80.90 KB)
convert 1.78 KB (gzip 0.98 KB)
html 307.87 KB (gzip 135.13 KB)
polyphonic 180.75 KB (gzip 78.83 KB)
Total 561.18 KB (gzip 158.13 KB)

Packages Docs En Docs Guide Changelog (`packages/docs/en/docs/guide/changelog.md`)

ChangeLog

3.29.5

  • 【feat】Add opt-in consecutive third-tone sandhi through toneSandhi.thirdTone while preserving the existing boolean toneSandhi semantics #356
  • 【perf】match: Reconstruct matching paths with backpointers to reduce array allocations #367
  • 【perf】match: Optimize prefix matching to avoid unnecessary string processing #369
  • 【perf】polyphonic: Reuse parsed final parts to avoid repeated work in type: 'all' mode #372
  • 【perf】match: Reuse split text characters to avoid repeated splitting #373
  • 【perf】Optimize node lookups and queue handling while building the AC automaton #374
  • 【perf】Batch consecutive custom-pinyin updates to reduce repeated custom dictionary rebuilds #375

3.29.4

  • 【fix】Tolerate runtimes that forbid timers during module initialization, such as Cloudflare Workers #364
  • 【perf】match: Reuse per-character pinyin forms in DP to avoid repeated computation #362、#360
  • 【perf】segmentit: Stop prebuilding the AC automaton via setTimeout in Node to further reduce import cost #361

3.29.3

Thank you @luojiyin1987 for continued optimizations to the segmentation module, the performance of the pinyin API has been further improved (about 20%+):

  • 【perf】segmentit: Avoid prefix string allocations when building the AC automaton #344
  • 【perf】segmentit: Reuse child lookup during AC matching #346
  • 【perf】segmentit: Reconstruct the max-probability path with backpointers #348
  • 【perf】splitString: Use a native split fast path for BMP-only text #349
  • 【perf】pinyin: Skip the reduplication processor when the text has no 々 #351

3.29.2

Thank you @luojiyin1987 for a series of optimizations, the performance of the pinyin API has been significantly improved (about 30%+):

  • 【perf】pinyin: Reuse parsed final in all output mode #342
  • 【fix】customPinyin: Prevent pattern accumulation on repeated updates #340
  • 【perf】pinyin: Reuse split characters across multiple middleware #338
  • 【perf】pinyin: Avoid splitting non-polyphonic pinyin with split #336

3.29.1

  • 【perf】Postpone the construction of the AC automaton to reduce main thread blocking when import pinyin-pro #333
  • 【perf】Optimize repeated calculations in middlewareMultiple #330
  • 【fix】Fix the issue where non-Chinese characters are not completely removed by nonZhScope #329

3.29.0

  • 【perf】Optimized the size of the match API in ESM mode, 306.81 KB (gzip 134.49 KB) > 185.44 KB (gzip 80.79 KB) #323
  • 【perf】Optimized ESM packaging configuration to ensure only necessary code is imported during tree shaking, reducing the size of each API #327

3.28.2

  • 【patch】Correct the following words in directory:

    diff
    行长: 'háng cháng', // [!code --]
    行长: 'háng zhǎng', // [!code ++]

3.28.1

  • 【feat】Added support for recognizing abbreviated forms of rhotic final sounds in the convert API #306

3.28.0

  • 【feat】Added addTraditionalDict API to better recognize traditional Chinese characters #303

3.27.0

  • 【feat】Added initialPattern option to the pinyin API to exclude y and w from the initial consonants #295

3.26.0

  • 【feat】Fixed the inconsistency in return values of first in pattern: 'first' mode and type: 'all': Modify it to consistently return the original non-Chinese characters for non-Chinese inputs. #278

3.25.0

  • 【feat】Added v option to the match API to allow using v to match ü #276

3.24.2

  • 【feat】Added rp option to the html API to remove <rp>(</rp> and <rp>)</rp> from the output #272
  • 【feat】When the custom class name in the html API is set to false or null, the default class name is retained #271

3.24.1

  • 【fix】Fixed the issue where the segment function would discard the last punctuation mark #268

3.24.0

  • 【feat】Added segment API for word segmentation #265
  • 【feat】Added nonZhScope property to the pinyin API to specify the scope of nonZh #266

3.23.1

  • patch: Corrected some pronunciations #260

3.23.0

  • 【feat】Support for external calls to getInitialAndFinal, getFinalParts, getNumOfTone, and other APIs #255

3.22.2

  • 【fix】Fixed .d.ts file errors caused by alias #253

3.22.1

  • 【patch】Corrected some entries in the word library #252
  • 【perf】Slight performance optimization #251

3.22.0

  • 【feat】Comprehensive adaptation of all APIs to support double Unicode encoded Chinese characters #242, #243, #247
  • 【feat】Support for all characters in the General Standard Chinese Character Table #244
  • 【feat】Support for the pronunciation of the repeated character 々 #245
  • 【feat】Support for pinyin characters like êê̄ếê̌ề #248
  • 【patch】Correct the default pronunciation of 曲: #249

3.21.1

  • 【fix】Fixed the issue where surname: 'head' did not work for compound surnames

3.21.0

  • 【feat】Added a surname option to the pinyin API, which supports recognizing surnames at the beginning of strings.

3.20.4

  • 【fix】Fixed TypeScript type errors caused by alias.

3.20.3

  • 【fix】Fixed an issue where the convert API incorrectly handled tone conversion for the iu finals.
  • 【patch】Corrected pronunciation for certain words, see details in #232.

3.20.2

  • 【fix】Addressed inconsistency in conversion behavior of polyphonic and pinyin for non-Chinese characters.

3.20.1

  • 【fix】Updated dictionary dependency versions.

3.20.0

  • 【feat】Support for customizing dictionaries through the addDict API.
  • 【feat】Added intelligent recognition of tone changes for 一 and 不, which can be controlled by the toneSandhi parameter to toggle on and off. Reference: Wikipedia
  • 【feat】Enhanced pronunciation recognition for 行, 斗, and 重 when preceded by numerical quantifiers.
  • 【feat】Added intelligent recognition of the pronunciation of 了 at the beginning of words.
  • 【feat】HTML API now includes the customClassMap option to add custom class names to specified characters.
  • 【feat】Implemented a new word segmentation algorithm, supporting dictionary input for more accurate segmentation.
  • 【feat】Added polyphonic and inZhRange properties to the all mode.
  • 【fix】Improved efficiency issue when using the customPinyin API.
  • 【fix】Resolved issues when using multiple and surname modes simultaneously.
  • 【fix】Addressed the problem in multiple mode where a non-Chinese character was lost when only one was present.
  • 【patch】Corrected the pronunciation of certain words.

3.19.6

3.19.5

  • 【fix】Fixed the issue where the first letter was not retrieved correctly in the pattern: 'first' mode for non-Chinese characters

3.19.4

  • 【fix】Fixed the issue of incorrect conversion of non-Chinese characters under the toneType: none parameter. #156

3.19.3

  • 【patch】Correct the directory:434cf51cd

3.19.2

  • 【patch】Correct the following words in directory:

    diff
    止咳: 'zhǐ ké',  // [!code ++]
    咳特灵: 'ké tè líng',  // [!code ++]

3.19.1

  • 【patch】Correct the following words in directory:

    diff
    那些: 'nèi xiē', // [!code --]
    皇上: 'huáng shang', // [!code --]
    太监: 'tài jiàn', // [!code --]
    审查: 'shěn zhā', // [!code --]
    只得: 'zhǐ de', // [!code --]
    哪些: 'něi xiē', // [!code --]
    一处: 'yī chǔ', // [!code --]
    大夫: 'dài fū', // [!code --]
    便宜: 'pián yí', // [!code --]
    哪个: 'něi gè', // [!code --]
    肚子: 'dǔ zi', // [!code --]
    难得: 'nán de', // [!code --]
    晓得: 'xiǎo de', // [!code --]
    寻思: 'xín sī', // [!code --]
    夺得: 'duó de', // [!code --]
    巴结: 'bā jì', // [!code --]
    了得: 'liǎo de', // [!code --]
    行家: 'háng jia', // [!code --]
    当夜: 'dàng yè', // [!code --]
    皇上: 'huáng shàng', // [!code ++]
    太监: 'tài jian', // [!code ++]
    审查: 'shěn chá', // [!code ++]
    大夫: 'dài fu', // [!code ++]
    便宜: 'pián yi', // [!code ++]
    难得: 'nán dé', // [!code ++]
    晓得: 'xiǎo dé', // [!code ++]
    寻思: 'xún si ', // [!code ++]
    夺得: 'duó dé', // [!code ++]
    巴结: 'bā jié', // [!code ++]
    了得: 'liǎo dé', // [!code ++]
    行家: 'háng jiā', // [!code ++]

3.19.0

  • 【Feature】: customPinyin: customPinyin now supports applying to multiple and polyphonic.

3.18.6

  • 【patch】Correct the following words in directory, for more details please see #148
  • 【fix】convert: support input v, for example: lv4 se4 -> lǜ sè

3.18.5

  • 【patch】Correct the following words in directory:

    diff
    否极泰来: 'pǐ jí tài lái', // [!code --]
    否往泰来: 'pǐ wǎng tài lái', // [!code --]
    否去泰来: 'pǐ qù tài lái', // [!code --]
    否极泰回: 'pǐ jí tài huí', // [!code --]
    泰来否往: 'tài lái pǐ wǎng', // [!code --]
    泰来否极: 'tai lái fǒu jí', // [!code --]
    唯唯否否: 'wěi wěi fǒu fǒu', // [!code --]
    臧否: 'zāng pǐ', // [!code ++]
    否泰: 'pǐ tài', // [!code ++]
    否极泰: 'pǐ jí tài', // [!code ++]
    泰来否: 'tài lái pǐ', // [!code ++]

3.18.4

  • 【patch】Correct the following words in directory:

    text
    只争朝夕: 'zhǐ zhēng zhāo xī', // [!code --]
    娉婷婀娜: 'pīng tíng ē nà', // [!code --]
    鸣凤朝阳: 'míng fèng zhāo yáng', // [!code --]
    凤鸣朝阳: 'fèng míng zhāo yáng', // [!code --]
    朝阳鸣凤: 'zhāo yáng míng fèng', // [!code --]
    朝成暮徧: 'cháo chéng mù shí', // [!code --]
    朝霞: 'zhāo xiá', // [!code ++]
    朝夕: 'zhāo xī', // [!code ++]
    朝气: 'zhāo qì', // [!code ++]
    翅膀: 'chì bǎng', // [!code ++]
    省长: 'shěng zhǎng', // [!code ++]
    一担水: 'yī dàn shuǐ', // [!code ++]

3.18.3

  • 【patch】Correct and add the following words to directory:
    • 衒玉贾石: zuì yù jiǎ shí -> zuì yù gǔ shí
    • 了却: liǎo què
    • 力气: lì qi
    • 席子: xí zi
    • 林子: lín zi

3.18.2

  • 【patch】Correct and add the following words to directory:
    • 瓶子: shàn zi-> píng zi
    • 镜子: jìng zi
    • 银子: yín zi
    • 盘子: pán zi

3.18.1

  • 【fix】Fix the issue of build failure in some Vue cli projects caused by bundler migration in 3.18.0

3.18.0

  • 【feat】match:An insensitive option has been added to set case-insensitive, default value is true
  • 【patch】Add the following words to directory:
    • 琵琶: pí pa
    • 蘑菇: mó gu
    • 葫芦: hú lu
    • 狐狸: hú li
    • 桔子: jú zi
    • 盒子: hé zi
    • 桌子: zhuō zi
    • 竹子: zhú zi
    • 师傅: shī fu
    • 衣服: yī fu
    • 袜子: wà zi
    • 杯子: bēi zi
    • 刺猬: cì wei
    • 麦子: mài zi
    • 队伍: duì wu
    • 知了: zhī liao
    • 鱼儿: yú er
    • 馄饨: hún tun
    • 灯笼: dēng long
    • 庄稼: zhuāng jia
    • 聪明: cōng ming

3.17.0

  • 【feat】Add convert API to convert the format of pinyin

3.16.7

  • 【patch】Add the following words to directory:
    • 成都: chéng dū
    • 都城: dū chéng
    • 六安: lù ān
    • 蚌埠: bèng bù
    • 崆峒: kōng tóng
    • 都江堰: dū jiāng yàn

3.16.6

  • 【patch】Add the following words to directory:
    • 嘴巴: 'zuǐ ba',
    • 耳朵: 'ěr duo',
    • 茄子: 'qié zi',

3.16.5

  • 【patch】Correct pronunciation related to relatives and '子'. For details, please refer to863c2e9

3.16.4

  • 【patch】Add the following words to directory:
    • 重启: chóng qǐ

3.16.3

  • 【optimize】Optimize the construction time of initializing AC automata

3.16.2

  • 【patch】Add following Chinese characters and Pinyin in surname mode:
    • 肖: xiāo

3.16.1

  • 【patch】Correct the Pinyin of following Chinese characters:

    • 苹: pín -> píng

3.16.0

  • 【feature】Add parameter separator of pinyin api to customize separator between pinyins, only effective when type: 'string'.

3.15.4

  • 【optimize】 esm eliminates compression confusion and solves the issue of ineffective use of tree shading

3.15.3

  • 【fix】 Resolve the issue of retaining alias path in .d.ts file

3.15.2

  • 【fix】 Optimize the esm build format to solve the issue of referencing errors in some node environments

3.15.1

  • 【fix】 Fix the types references in package.json

3.15.0

  • 【feat】 Add html API to get a HTML string of Chinese characters and Pinyin
  • 【feat】 Add polyphonic API to get all Pinyins of Chinese characters
  • 【feat】 Rewrite match API, add parameter to control matching rules
  • 【patch】Correct the Pinyin of Some Chinese characters and words:
    • 屏: bīng píng bǐng -> píng bǐng bīng
    • 呒: ḿ -> fǔ ḿ
    • 吋: cùn yīngcùn -> cùn dòu
    • 呎: chǐ yīngchǐ -> chǐ
    • 蝊: uu -> dìng
    • 噷: hm hěn xīn hèn -> xīn hěn hèn
    • 唡: liǎng yīngliǎng -> liǎng
    • 曢: uu -> liǎo
    • 呣: ḿ m̀ -> ḿ m̀ móu
    • 聁: uu -> pàn
    • 闧: uu -> tā
    • 屗: uu -> wěi
    • 虲: uu -> xiā
    • 屏气吞声: píng qì tūn shēng -> bǐng qì tūn shēng
    • 敛声屏息: liǎn shēng píng xī -> liǎn shēng bǐng xī
    • Remove the following Chinese characters:
      • 瓸: 'bǎiwǎ'
    • Add the following Chinese words:
      • 好好: hǎo hǎo

3.14.0

  • 【refactor】Using Aho–Corasick_algorithm to optimize pinyin matching speed and improve performance by nearly 50 times!
  • 【patch】Correct the Pinyin of Some Chinese characters and words:
    • 种: zhòng zhǒng chóng -> zhǒng zhòng chóng
    • Remove unnecessary Chinese words related to 种(zhǒng)
    • Add the following Chinese words:
      • 耕种: gēng zhòng
      • 种地: zhòng dì
      • 种菜: zhòng cài
      • 栽种: zāi zhòng
      • 接种: jiē zhòng
      • 垦种: kěn zhòng
      • 种殖: zhòng zhí
      • 种瓜: zhòng guā
      • 种豆: zhòng dòu
      • 种树: zhòng shù
      • 睡着: shuì zháo
      • 笼子: lóng zi
      • 厦门: xià mén
      • 东莞: dōng guǎn

3.13.2

  • 【patch】Correct the Pinyin of Some Chinese characters and words:
    • 皇甫: huáng pǔ -> huáng fǔ
    • 一丁点儿: yī dīng diǎnr -> yī dīng diǎn er

3.13.1

  • 【fix】pinyin:Fix conflicts when using both multiple and name in the options parameter
  • 【patch】Correct the Pinyin of Some Chinese characters and words

3.13.0

  • 【fix】pinyin:Fix the issue of duplicate pinyin when using multiple: true and toneType: none simultaneously in the options parameter

3.12.0

  • 【feat】pinyin:options.pattern parameter adds optional values finalHead、finalBody and finalTail.
  • 【feat】pinyin:options.type parameter adds optional value all to get all the data of Pinyin
  • 【fix】pinyin:Fix the issue of incorrect output results when the text parameter contains spaces and options.type is array

3.11.0

  • 【perf】Optimize the Pinyin vocabulary to improve the accuracy
  • 【perf】Reduce the size of package by approximately 10%
  • 【feat】match:New support for Chinese matching and mixed Chinese and Pinyin matching

3.10.2

  • 【patch】Correct the Pinyin of Some Chinese characters and words:
    • 责: zhài -> zé zhài
    • 朝阳: zhāo cháo yáng -> cháo yáng
    • 假发: jiǎ fā -> jiǎ fà
  • 【perf】Optimize prompts of typescript

3.10.1

  • 【patch】Correct the Pinyin of Some Chinese characters and words:
    • 哼: hng -> hēng hng

3.10.0

  • 【perf】Reduce the size of package by approximately 30%

3.9.0

  • 【feat】pinyin:The options parameter adds an optional attribute of v. When options.v is true, the ü in Pinyin will ebe replaced by v.

3.8.3

  • 【patch】Correct the Pinyin of Some Chinese characters and words:
    • 查岗: zhā gǎng -> chá gǎng
    • 查核: zhā hé -> chá hé
    • 查缉: zhā jī -> chá jī
    • 查检: zhā jiǎn -> chá jiǎn
    • 查看: zhā kàn -> chá kàn
    • 查勤: zhā qín -> chá qín
    • 查帐: zhā zhàng -> chá zhàng
    • 查照: zhā zhào -> chá zhào

3.8.2

  • 【fix】pinyin:Fix again the issue of incorrect default values returned by double byte unicode encoded text

3.8.1

  • 【fix】pinyin:Fix the issue of incorrect default values returned by double byte unicode encoded text

3.8.0

  • 【feat】pinyin:The options parameter adds an optional attribute nonZh to configure the output for non Chinese Characters.

3.7.2

  • 【patch】Correct the Pinyin of Some Chinese characters and words:
    • 物美价廉: jià lián wù měi -> wù měi jià lián

3.7.1

  • 【fix】pinyin:Fix the issue of pinyin conversion errors when options.toneType is none for 嗯

3.7.0

  • 【perf】Support for dynamic introduction of ESM

3.6.2

  • 【fix】pinyin:Fix the issue of not prioritizing matching custom pinyin when using both the customPinyin API and options.mode is surname simultaneously.
  • 【fix】pinyin:Fix the issue of incorrect pinyin for some surnames.

3.6.1

  • 【fix】pinyin:Fix memory overflow when options.removeNonZh is true and all input strings are non Chinese Characters.

3.6.0

  • 【feat】pinyin:The options parameter adds an optional attribute of removeNonZh, when options.removeNonZh is true, output of non Chinese characters will be removed.

3.5.0

  • 【feat】Add the match API to support pinyin text matching.

3.4.1

  • 【fix】pinyin:Fix the issue of invalid tone acquisition when options.toneType is num and options.pattern is first or options.pattern is initial.

3.4.0

  • 【feat】pinyin:The options parameter adds an optional attribute mode. When options.mode is surname, support Pinyin recognition with surname pattern.
  • 【feat】Add customPinyin api,Support user customize pinyin.
  • 【fix】Fix memory overflow issue when text is too long.
  • 【patch】Correct the Pinyin of Some Chinese characters and words:
    • 褚: zhǔ -> chǔ zhǔ
    • 俞: yù -> yú yù
    • 臧: zàng -> zāng
    • 贲: bì -> bēn bì
    • 莘: xīn -> shēn xīn
    • 郦: zhí -> lì zhí

3.3.1

  • 【fix】Fix memory overflow issue when text is too long.

3.3.0

  • 【perf】Optimize the pinyin conversion speed, it has increased by nearly 30 times!

3.2.3

  • 【perf】Optimize prompts of typescript.
  • 【perf】Optimize pinyin conversion algorithm to improve conversion speed.

3.2.2

  • 【fix】pinyin:Fix the error issue of not finding polyphonic results when options is { multiple: true, type: 'array ' }

3.2.1

  • 【patch】Correct the Pinyin of Some Chinese characters and words:
    • 艾: yì -> ài yì
    • 吽: ōu -> hōng hǒu ōu

3.2.0

  • 【perf】Adjust the dictionary order based on the frequency of single word usage to improve performance, and increase the conversion speed of long sentences by 100%.
  • 【patch】Correct the Pinyin of Some Chinese characters and words:
    • 啊: ā -> a
    • 阿: ē -> ā
  • 【perf】Support the use of <script />

3.1.0

  • 【feat】pinyin:options.pattern adds an optional value first to get the first character of Pinyin.
  • 【docs】Fix the typo in Readme.

3.0.7

  • 【perf】Remove the readme option from package.json

3.0.6

  • 【docs】Fix version update document link error in Readme

3.0.5

  • 【docs】Optimize the QR code size of README.md documents

3.0.4

  • 【docs】README.md add QR Code

3.0.3

  • 【lint】Add eslintrc specification code quality.

3.0.2

  • 【perf】Optimize npm package quality and README.md

3.0.1

  • 【fix】Fix issue with no index.d.ts

3.0.0

  • 【refactor】Refactored the project using typescript + rollup

Packages Docs En Docs Guide Compare (`packages/docs/en/docs/guide/compare.md`)

Introduction

pinyin-pro is a professional JavaScript library for converting Chinese to Pinyin, with high accuracy, lightweight size, excellent performance, and rich functionality.

Among similar products, pinyin-pro has achieved a leading position in terms of accuracy, size, performance, functional richness and so on. The following are specific comparative data on performance and accuracy with similar competitors pinyin and @napi-rs/pinyin.

Test Environment

  • Device:
    • Brand and model: Lenovo XiaoXinPro-13ARE 2020
    • System:Windows10
    • RAM:16 GB
    • CPU: AMD Ryzen 7 4800U 1.8GHz
  • Runtime Environment: Nodejs v18.12.1

Benchmark

Comparison item pinyin @napi-rs/pinyin pinyin-pro
Accuracy 😕 Node 版: 94.097% 😕 94.097% 🤩 99.846%
😕 Web 版: 91.170%
Performance Dictionary initialization on first use 🚀 14.261ms 🐢 160.769ms 🚀 8.412ms
10,000 Chinese characters 🚲 74.442ms 🚀 4.298ms 🚀 7.216ms
100,000 Chinese characters 🐢 6287.332ms 🚀 29.32ms 🚀 45.471ms
1,000,000 Chinese characters ⛔ Out Of Memory 🚀 297.41ms 🚀 328.338ms
10,000,000 Chinese characters ⛔ Out Of Memory 🚀 3907.278ms 🚀 3375.192ms
Compatibility Browser ✔️ Supported ❌ Not Supported ✔️ Supported
Node ✔️ Supported ✔️ Supported ✔️ Supported

Data Source

  • More details on accuracy testing data: accuracy
  • More details on performance testing data: speed

Packages Docs En Docs Guide Start (`packages/docs/en/docs/guide/start.md`)

Get Started

Environment

pinyin-pro can run in Browser and Nodejs.

Installation

pinyin-pro can be installed by the package manager or imported through <script /> tag.

Package Managers

Recommend using package managers for installation:

perl
# pick your favorite package manager

# NPM
$ npm install pinyin-pro --save

# Yarn
$ yarn add pinyin-pro

# pnpm
$ pnpm install pinyin-pro

You can also import CDN files through the <script /> tag to use it, taking two CDN manufacturers unpkg and jsDelivr as examples:

unpkg

html
<head>
  <script src="https://unpkg.com/[email protected]/dist/index.js"></script>
</head>


<head>
  <script src="https://unpkg.com/pinyin-pro"></script>
</head>

jsDelivr

html
<head>
  <script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/index.js"></script>
</head>


<head>
  <script src="https://cdn.jsdelivr.net/npm/pinyin-pro"></script>
</head>

::: tip
We suggest that users who use CDN to introduce pinyin-pro lock the version on the link address and introduce it as a fixed version to avoid being affected by incompatible updates during future pinyin-pro upgrades. If you have your own CDN, it is also recommended to download and host the pinyin-pro script on your own CDN to avoid the impact of third-party CDN instability.
:::

Use

Support multiple environments and modular standardized usage methods.

ESM

js
import { pinyin } from 'pinyin-pro';

pinyin('汉语拼音'); // 'hàn yǔ pīn yīn'

Dynamic Import

js
import('pinyin-pro').then((exports) => {
  exports.pinyin('汉语拼音'); // 'hàn yǔ pīn yīn'
});

When you import pinyin-pro by <script />, the script will globally mount a variable named pinyinPro.

html
<script src="https://unpkg.com/pinyin-pro"></script>

<script>
  var { pinyin } = pinyinPro;
  pinyin('汉语拼音'); // 'hàn yǔ pīn yīn'
</script>

CommonJS

js
const { pinyin } = require('pinyin-pro');

pinyin('汉语拼音'); // 'hàn yǔ pīn yīn'

Packages Docs En Docs More Contact (`packages/docs/en/docs/more/contact.md`)

Contact Me

For any usage problems, you can join the QQ group 1042725850 or add the author's WeChat account zhoulx1688888 for consultation and feedback:


Packages Docs En Docs Run Run (`packages/docs/en/docs/run/run.md`)

Running Online

APIs such as pinyin, match, html,polyphonic and customPinyin have been automatically imported from' pinyin-pro without the need for manual import.


Packages Docs En Docs Use AddDict (`packages/docs/en/docs/use/addDict.md`)

addDict

pinyin-pro has built-in dictionaries for some commonly used high-frequency words. To ensure high accuracy, you may need to apply more comprehensive dictionaries using the addDict function. For more detail, see @pinyin-pro/data.

Install via npm install @pinyin-pro/data.

Examples

Using the Built-in Dictionary (Default)

The default dictionary has fewer vocabulary entries, for example, it does not include 日本京都大学, which may result in incorrect pronunciation recognition for 都:

js
import { pinyin } from 'pinyin-pro';

const result1 = pinyin('小明硕士毕业于中国科学院计算所,后在日本京都大学深造');
// Result: xiǎo míng shuò shì bì yè yú zhōng guó kē xué yuàn jì suàn suǒ , hòu zài rì běn jīng dōu dà xué shēn zào

Using the Modern Chinese Dictionary

Includes 日本京都大学, enabling accurate recognition (approximately 0.6MB after gzip compression, decide based on your needs whether to use it):

js
import { pinyin, addDict } from 'pinyin-pro';
// Import after installing via `npm install @pinyin-pro/data`
import ModernChineseDict from '@pinyin-pro/data/modern';

addDict(ModernChineseDict);

const result = pinyin('小明硕士毕业于中国科学院计算所,后在日本京都大学深造');
// Result: xiǎo míng shuò shì bì yè yú zhōng guó kē xué yuàn jì suàn suǒ , hòu zài rì běn jīng dū dà xué shēn zào

Using the Complete Dictionary

Includes more words for higher recognition accuracy (approximately 3.99MB after gzip compression, decide based on your needs whether to use it):

js
import { pinyin, addDict } from 'pinyin-pro';
// Import after installing via `npm install @pinyin-pro/data`
import CompleteDict from '@pinyin-pro/data/complete';

addDict(CompleteDict);

const result = pinyin('小明硕士毕业于中国科学院计算所,后在日本京都大学深造');
// Result: xiǎo míng shuò shì bì yè yú zhōng guó kē xué yuàn jì suàn suǒ , hòu zài rì běn jīng dū dà xué shēn zào

Syntax and Parameters

Syntax

ts
import { addDict } from 'pinyin-pro';

type DICT = {
  [key: string]:
    | string // Pinyin
    | [string] // [Pinyin]
    | [string, number] // [Pinyin, Frequency Probability]
    | [string, number, string]; // [Pinyin, Frequency Probability, Part of Speech]
};

function addDict(dict: DICT | {}, name?: string): void;

Parameters

  • dict (required): The dictionary.
  • name (optional): The name of the dictionary.

Packages Docs En Docs Use Convert (`packages/docs/en/docs/use/convert.md`)

convert

Using convert to convert the format of pinyin.

Example

Different formats

Support numToSymbol、symbolToNum、toneNone and so on:

js
import { convert } from 'pinyin-pro';

// numToSymbol
convert('pin1 yin1'); // 'pīn yīn'

// symbolToNum
convert('pīn yīn', { format: 'symbolToNum' }); // 'pin1 yin1'

// toneNone
convert('pīn yīn', { format: 'toneNone' }); // 'pin yin'
convert('pin1 yin1', { format: 'toneNone' }); // 'pin yin'

Array

Supports input in array format, and returns array format after conversion:

js
import { convert } from 'pinyin-pro';

convert(['pin1', 'yin1']); // ['pīn', 'yīn']

Specify separator

When the input is in string format, the separator can be specified through the separator parameter:

js
import { convert } from 'pinyin-pro';

convert('pin1-yin1', { separator: '-' }); // 'pīn-yīn'

API

Function

js
import { convert } from 'pinyin-pro';

interface ConvertOptions {
  /**
   * @description specify the separator
   */
  separator?: string;
  /**
   * @description format of conversation, default value is numToSymbol
   * @example numToSymbol: pin yin -> pīn yīn
   * @example symbolToNum: pīn yīn -> pin yin
   * @example toneNone: pīn yīn -> pin yin
   */
  format?: ConvertFormat;
}

function convert(pinyin: string | string[], options?: ConvertOptions): string | string[];

Parameters

  • pinyin (required):string | string[], the pinyin string or array of pinyin strings to convert
  • options (optional): object, the configuration of conversion rules:
Attribute Type Description Optional Values Detail Default Value
separator string the separator specified - convert function will split pinyin with this separator for conversion ' '
format string format of conversion numToSymbol convert number to symbol numToSymbol
SymbolToNum convert symbol to number
toneNone remove symbol in pinyin

Packages Docs En Docs Use CustomPinyin (`packages/docs/en/docs/use/customPinyin.md`)

customPinyin

customPinyin api allows users to customize the pinyin of words and sentences. When Chinese matches the user defined pinyin of words and sentences, the user defined pinyin is preferred.

Example

Without customPinyin

When it comes to polyphonic characters, some complex pinyin or person names may not be accurately recognized, for example, if you have a person named 张会(zhāng kuài)

js
import { pinyin } from 'pinyin-pro';

pinyin('他叫张会'); // 'tā jiào zhāng huì'

With customPinyin

Using the customPinyin api, you can supplement this section with inaccurate pinyin recognition yourself.

js
import { pinyin, customPinyin } from 'pinyin-pro';

customPinyin({
  张会: 'zhāng kuài',
});

pinyin('他叫张会'); // 'tā jiào zhāng kuài'

Apply to `multiple` and `polyphonic`

By appending multiple and polyphonic in the second parameter of customPinyin, you can make it effective for multiple and polyphonic.

When the values of multiple or polyphonic are add, the pinyin of the characters will be appended on the original base. When it is replace, it will directly overwrite the original base.

js
// Example of appending
customPinyin({
  张会: 'zhāng huài',
}, {
  multiple: 'add',
  polyphonic: 'add',
});

pinyin('张', { multiple: true }); // 'zhāng' (Zhang was already present, no need to append additionally)
pinyin('会', { multiple: true }); // 'huì kuài huài' (Append huài to the existing data)

polyphonic('张会'); // ["zhāng", "huì kuài huài"]
js
// Example of replacing
customPinyin({
  张会: 'zhāng huài',
}, {
  multiple: 'replace',
  polyphonic: 'replace',
});

pinyin('张', { multiple: true }); // 'zhāng' (Replace with zhāng)
pinyin('会', { multiple: true }); // 'huài' (Replace with huài)

polyphonic('张会'); // ["zhāng", "huài"]

Clearing Original Custom Data

By default, the data supplemented by multiple calls to customPinyin accumulates. You can use clearCustomDict to clear the original data.

js
import { clearCustomDict } from 'pinyin-pro';

// Clear custom data for pinyin api
clearCustomDict('pinyin');
// Clear custom data for pinyin api in multiple pattern
clearCustomDict('multiple');
// Clear custom data for polyphonic api
clearCustomDict('polyphonic');
// Clear all custom data
clearCustomDict(['pinyin', 'multiple', 'polyphonic']);

API

Function

ts
import { customPinyin, clearCustomDict } from 'pinyin-pro';

interface PinyinMap {
  [key: string]: string;
}

type CustomHandleType = 'add' | 'replace';

type CustomDictType = 'pinyin' | 'multiple' | 'polyphonic';

interface CustomPinyinOptions {
  multiple?: CustomHandleType;
  polyphonic?: CustomHandleType;
}

function customPinyin(map: PinyinMap, options?: CustomPinyinOptions);

function clearCustomDict(dict: CustomDictType | CustomDictType[]);

Parameters

  • map (required): object, customized pinyin mapping, where key is a Chinese character and value is pinyin.
  • options (optional): object, specifying whether to enable and how to apply multiple and polyphonic.

Packages Docs En Docs Use Html (`packages/docs/en/docs/use/html.md`)

html

Use html API to get a HTML string of Chinese characters and Pinyin in the format of ''.

Example

Basic Use

The returned value of html api is a HTML string:

  • The outermost layer of each Chinese character and Pinyin is wrapped by a `` tag. (the class of the tag can be customized through the resultClass attribute)
  • The inner layer is wrapped with <ruby></ruby> to display Chinese characters and Pinyin.
  • The Chinese character part is wrapped by a `` tag. (the class of the tag can be customized through the chineseClass attribute)
  • The Pinyin part is wrapped by a <rt class="py-pinyin-item"></rt> tag. (the class of the tag can be customized through the pinyinClass attribute)
  • By default, non Chinese character isn't be wrapped. By setting the value of the wrapNonChinese attribute to true, non Chinese character part will be wrapped by a `` tag. (The class of the tag can be customized through the nonChineseClass attribute)
js
import { html } from 'pinyin-pro';

const htmlString = html('汉语拼音');

/*
<span class="py-result-item">
  <ruby>
    <span class="py-chinese-item">汉</span>
    <rp>(</rp>
    <rt class="py-pinyin-item">hàn</rt>
    <rp>)</rp>
  </ruby>
</span>
<span class="py-result-item">
  <ruby>
    <span class="py-chinese-item">语</span>
    <rp>(</rp>
    <rt class="py-pinyin-item">yǔ</rt>
    <rp>)</rp>
  </ruby>
</span>
<span class="py-result-item">
  <ruby>
    <span class="py-chinese-item">拼</span>
    <rp>(</rp>
    <rt class="py-pinyin-item">pīn</rt>
    <rp>)</rp>
  </ruby>
</span>
<span class="py-result-item">
  <ruby>
    <span class="py-chinese-item">音</span>
    <rp>(</rp>
    <rt class="py-pinyin-item">yīn</rt>
    <rp>)</rp>
  </ruby>
</span>
*/

The preview of the htmlString in the browser is as follows:

Without Tone

When set the value of the toneType attribute to none, the Pinyin in the returned value has no tone.

js
import { html } from 'pinyin-pro';

const htmlString = html('汉语拼音', { toneType: 'none' });

/*
<span class="py-result-item">
  <ruby>
    <span class="py-chinese-item">汉</span>
    <rp>(</rp>
    <rt class="py-pinyin-item">han</rt>
    <rp>)</rp>
  </ruby>
</span>
<span class="py-result-item">
  <ruby>
    <span class="py-chinese-item">语</span>
    <rp>(</rp>
    <rt class="py-pinyin-item">yu</rt>
    <rp>)</rp>
  </ruby>
</span>
<span class="py-result-item">
  <ruby>
    <span class="py-chinese-item">拼</span>
    <rp>(</rp>
    <rt class="py-pinyin-item">pin</rt>
    <rp>)</rp>
  </ruby>
</span>
<span class="py-result-item">
  <ruby>
    <span class="py-chinese-item">音</span>
    <rp>(</rp>
    <rt class="py-pinyin-item">yin</rt>
    <rp>)</rp>
  </ruby>
</span>
*/

The preview of the above code in the browser is as follows:

Custom Style

You can control the specific style by using the class in the returned value of html api. In the following example, we let the Chinese character part in blue and the Pinyin part in red.

js
// js
import { html } from 'pinyin-pro';

const htmlString = html('汉语拼音');
css
/* css */
.py-chinese-item {
  color: blue;
}
.py-pinyin-item {
  color: red;
}

The preview of the above code in the browser is as follows:

Custom Classes of Designated Words

You can apply individual styles to specific characters through the customClassMap parameter. For example, in the following example, the "汉" part is in red, and the "音" part is in blue.

js
import { html } from 'pinyin-pro';

const htmlString = html('汉语拼音', {
  customClassMap: {
    'red-item': ['汉'],
    'blue-item': ['音'],
  },
});

/*
<span class="py-result-item red-item">
	<ruby>
		<span class="py-chinese-item">汉</span>
		<rp>(</rp>
		<rt class="py-pinyin-item">hàn</rt>
		<rp>)</rp>
	</ruby>
</span>
<span class="py-result-item">
	<ruby>
		<span class="py-chinese-item">语</span>
		<rp>(</rp>
		<rt class="py-pinyin-item">yǔ</rt>
		<rp>)</rp>
	</ruby>
</span>
<span class="py-result-item">
	<ruby>
		<span class="py-chinese-item">拼</span>
		<rp>(</rp>
		<rt class="py-pinyin-item">pīn</rt>
		<rp>)</rp>
	</ruby>
</span>
<span class="py-result-item blue-item">
	<ruby>
		<span class="py-chinese-item">音</span>
		<rp>(</rp>
		<rt class="py-pinyin-item">yīn</rt>
		<rp>)</rp>
	</ruby>
</span>
*/
css
/* css */
.red-item {
  color: red;
}
.blue-item {
  color: blue;
}

The preview of the above code in the browser is as follows:

API

Function

ts
import { customPinyin } from 'pinyin-pro';

interface HtmlOptions {
  resultClass?: string;
  pinyinClass?: string;
  chineseClass?: string;
  wrapNonChinese?: boolean;
  nonChineseClass?: string;
  tone?: boolean;
  rp?: boolean; // v3.24.2+  Whether to output <rp>(</rp> and <rp>)</rp> tags
  toneType?: 'symbol' | 'num' | 'none';
  v?: boolean;
  segmentit?: TokenizationAlgorithm; // v3.20.0+
  surname?: 'off' | 'head' | 'all'; // v3.21.0+
  mode?: 'normal' | 'surname'; // deprecated, use surname to replace
  toneSandhi?: boolean | { yi?: boolean; bu?: boolean; thirdTone?: boolean };
  initialPattern?: 'standard' | 'yw'; // 3.27.0+
  traditional?: boolean; // 3.28.0+
}

function html(text: string, options?: HtmlOptions): string {}

Parameters

  • text (required): string, the Chinese character string to convert.
  • options (optional): object, the configuration related to the return value, more specific information is shown in the table below:
Key Type Description Optional Values Default Value
resultClass string class of the outermost &lt;span&gt; tag of Chinese characters and pinyin - py-result-item
pinyinClass string class of the outer &lt;rt&gt; tag of Pinyin - py-pinyin-item
chineseClass string class of the outer &lt;span&gt; tag of Chinese character - py-chinese-item
wrapNonChinese string Whether use &lt;span&gt; to wrap non Chinese characters. If you want to do some custom style processing for non Chinese characters, it is recommended to set it to true; If the input text parameter is also an HTML string, it is recommended to set it to false to prevent affecting the structure of the text. true/false false
nonChineseClass string class of the outer &lt;span&gt; tag of non Chinese character(Only when the value of wrapNonChinese is true, it is work.) - py-non-chinese-item
toneType string the display form of tones in Pinyin symbol/none/num symbol

Packages Docs En Docs Use Match (`packages/docs/en/docs/use/match.md`)

match

Using match api to match Chinese text string with pinyin string.

Example

Basic Use

If Pinyin matches text, return the indexes of the matching text.

js
import { match } from 'pinyin-pro';

match('汉语拼音', 'hanyupinyin'); // [0, 1, 2, 3]

Continuous

Using the continuous attribute to specify whether the matching Chinese indexes are continuous is considered a successful match (the default value is false, which means continuous matching is not required):

js
import { match } from 'pinyin-pro';

match('汉语拼音', 'hanpin'); // [0, 2]

match('汉语拼音', 'hanpin', { continuous: true }); // null

Precision

The precision attribute can be used to control the accuracy of Chinese character and Pinyin matching:

js
import { match } from 'pinyin-pro';

// 默认首字母匹配算匹配成功
match('中文拼音', 'zwpy'); // [0, 1, 2, 3]

// every 需要每一个字符都匹配成功
match('中文拼音', 'zwpy', { precision: 'every' }); // null
match('中文拼音', 'zhongwenpinyin', { precision: 'every' }); // [0, 1, 2, 3]

// start 只要开头任意个字母匹配就算匹配成功
match('中文拼音', 'zhwpy', { precision: 'start' }); // [0, 1, 2, 3]
match('中文拼音', 'zhwpy'); // null

// any 任意有一个字母匹配就算匹配成功
match('中文拼音', 'ongwpy', { precision: 'any' }); // [0, 1, 2, 3]
match('中文拼音', 'ongwpy'); // null

Space

Use the space attribute to control whether the spaces don't participate in matching:

js
import { match } from 'pinyin-pro';

// 默认不参与匹配
match('汉语拼音', 'han yupinyin'); // [0, 1, 2, 3]

match('汉语拼音', 'han yupinyin', { space: 'preserve' }); // null

lastPrecision

The lastPrecision attribute can be used to control the accuracy of matching the last Chinese character with Pinyin. By default, when the precision is any the lastPrecision is any; Otherwise, lastPrecision is start'.

js
import { match } from 'pinyin-pro';

// default
match('汉语拼音', 'hanyupiny'); // [1, 2, 3, 4]

// specify lastPrecision
match('汉语拼音', 'hanyupiny', { lastPrecision: 'every' }); // null

Polyphonic Matching

For polyphonic characters, as long as one of the Pinyins matches, the matching is considered successful:

js
import { match } from 'pinyin-pro';

match('会计', 'kuaiji'); // [0, 1]
match('会计', 'huiji'); // [0, 1]

v match ü

The v attribute can be used to allow using v to match ü:

js
import { match } from 'pinyin-pro';

match('吕布', 'lvbu'); // [0, 1]

API

Function

js
import { match } from 'pinyin-pro';

interface MatchOptions {
  precision?: 'first' | 'start' | 'every' | 'any';
  continuous?: boolean;
  space?: 'ignore' | 'preserve';
  lastPrecision?: 'first' | 'start' | 'every' | 'any';
  v?: boolean; // v3.25.0+
}

function match(text: string, pinyin: string, options?: MatchOptions): number[] | null; // 匹配成功返回匹配汉字对应下标数组; 不成功返回 null

Parameters

  • text (required):string, Chinese text to match
  • pinyin (required):string, Pinyin to match
  • options (optional): object, the configuration of matching rules, more specific information is shown in the table below:
Attribute Type Description Optional Values Detail Default Value
precision string matching accuracy first matching is considered successful when the initial letter or full pinyin is equal to the current pinyin first
start starting with the current pinyin is considered a successful match
every full Pinyin and current Pinyin are strictly equal in order to be considered a successful match
any containing all characters of the current pinyin are considered as successful matches
continuous boolean Whether the matching Chinese indexes need to be continuous in order to be considered successful true not required false
false required
space string handling of spaces in Chinese characters and pinyin during matching ignore ignore ignore
preserve preserve
lastPrecision string the accuracy of the last character matching first Matching is considered successful when the initial letter or full pinyin is equal to the current pinyin By default, when the precision is any, lastPrecision is any; Otherwise lastPrecision is start
start starting with the current pinyin is considered a successful match
every full Pinyin and current Pinyin are strictly equal in order to be considered a successful match
any containing all characters of the current pinyin are considered as successful matches
v boolean Whether to allow using v to match ü true allow using v to match ü false
false not allow using v to match ü

Packages Docs En Docs Use Others (`packages/docs/en/docs/use/others.md`)

pinyin

The pinyin-pro package also exports some intermediate processing functions for users to utilize.

getInitialAndFinal

You can use getInitialAndFinal to obtain the initial (consonant) and final (vowel) parts of a specified pinyin:

js
import { getInitialAndFinal } from 'pinyin-pro';

const result = getInitialAndFinal('guang');
/* The result is:
{
  final: 'uang',
  initial: 'g',
}
*/

getFinalParts

You can use getFinalParts to obtain the medial, nucleus, and coda of a specified pinyin:

js
import { getFinalParts } from 'pinyin-pro';

const result = getFinalParts('guang');
/* The result is:
{
  head: "u",
  body: "a",
  tail: "ng",
}
*/

getNumOfTone

You can use getNumOfTone to obtain the numerical representation of the tones for a specified pinyin:

js
import { getNumOfTone } from 'pinyin-pro';

const result = getNumOfTone('hàn yǔ de pīn yīn');
/* The result is:
"4 3 0 1 1"
*/

Packages Docs En Docs Use Pinyin (`packages/docs/en/docs/use/pinyin.md`)

pinyin

Using pinyin api to convert Chinese into Pinyin and related content.

Example

Pinyin

The options.type parameter controls the format of the returned value, and the options.toneType parameter controls the display format of tones in Pinyin.

js
import { pinyin } from 'pinyin-pro';

// Get Pinyin with Tones
pinyin('汉语拼音'); // 'hàn yǔ pīn yīn'
// Get Pinyin without Tones
pinyin('汉语拼音', { toneType: 'none' }); // 'han yu pin yin'
// Get Pinyin where the tone is converted to a numerical suffix
pinyin('汉语拼音', { toneType: 'num' }); // 'han4 yu3 pin1 yin1'
// Get Pinyin with Tones in array form
pinyin('汉语拼音', { type: 'array' }); // ["hàn", "yǔ", "pīn", "yīn"]
// Get Pinyin without Tones in array form
pinyin('汉语拼音', { toneType: 'none', type: 'array' }); // ["han", "yu", "pin", "yin"]
// Get Pinyin where the tone is converted to a numerical suffix in array form
pinyin('汉语拼音', { toneType: 'num', type: 'array' }); // ["han4", "yu3", "pin1", "yin1"]

Initial consonants

When options.pattern is initial, the returned value is initials of Pinyin.

js
import { pinyin } from 'pinyin-pro';

// Get initial consonants of Pinyin
pinyin('汉语拼音', { pattern: 'initial' }); // 'h y p y'
// Get initial consonants of Pinyin in array form
pinyin('汉语拼音', { pattern: 'initial', type: 'array' }); // ["h", "y", "p", "y"]

Finals

When options.pattern is final, the returned value is finals of Pinyin.

js
import { pinyin } from 'pinyin-pro';

// Get vowels of Pinyin with Tones
pinyin('汉语拼音', { pattern: 'final' }); // 'àn ǔ īn īn'
// Get vowels of Pinyin without Tones
pinyin('汉语拼音', { pattern: 'final', toneType: 'none' }); // 'an u in in'
// Get vowels of Pinyin where the tone is converted to a numerical suffix
pinyin('汉语拼音', { pattern: 'final', toneType: 'num' }); // 'an4 u3 in1 in1'
// Get vowels of Pinyin with Tones in array form
pinyin('汉语拼音', { pattern: 'final', type: 'array' }); // ["àn", "ǔ", "īn", "īn"]
// Get vowels of Pinyin without Tones in array form
pinyin('汉语拼音', { pattern: 'final', toneType: 'none', type: 'array' }); // ["an", "u", "in", "in"]
// Get vowels of Pinyin where the tone is converted to a numerical suffix in array form
pinyin('汉语拼音', { pattern: 'final', toneType: 'num', type: 'array' }); // ['an4', 'u3', 'in1', 'in1']

Head/Essential/Tail Vowel

When options.pattern is finalHead/finalBody/finalTail, the returned value is head vowel/essential vowel/tail vowel.

js
import { pinyin } from 'pinyin-pro';

// Get the head vowel of pinyin in array form
pinyin('村庄', { pattern: 'finalHead', type: 'array' }); // [ '', 'u' ]

// Get the essential vowel of pinyin in array form
pinyin('村庄', { pattern: 'finalBody', type: 'array' }); // [ 'ū', 'ā' ]

// Get the tail vowel of pinyin in array form
pinyin('村庄', { pattern: 'finalTail', type: 'array' }); // [ 'n', 'ng' ]

Tones

When options.pattern is num, the returned value is the tone of pinyin.

js
import { pinyin } from 'pinyin-pro';

// Get the tone of pinyin
pinyin('汉语拼音', { pattern: 'num' }); // '4 3 1 1'
// Get the tone of pinyin in array form
pinyin('汉语拼音', { pattern: 'num', type: 'array' }); // ["4", "3", "1", "1"]

First Character

When options.pattern is first, the returned value is first character of pinyin.

js
import { pinyin } from 'pinyin-pro';

// Get the first character of pinyin
pinyin('赵钱孙李额', { pattern: 'first' }); // 'z q s l é'
// Get the first character of pinyin without tones
pinyin('赵钱孙李额', { pattern: 'first', toneType: 'none' }); // 'z q s l e'
// Get the first character of pinyin in array form
pinyin('赵钱孙李额', { pattern: 'first', type: 'array' }); // ['z', 'q', 's', 'l', 'é']
// Get the first character of pinyin without tones in array forms
pinyin('赵钱孙李额', { pattern: 'first', toneType: 'none', type: 'array' }); // ['z', 'q', 's', 'l', 'e']

All Content

When options.type is all, the returned value is all content of pinyin in array form.

js
const result = pinyin('汉语拼音', { type: 'all' });

/**
[
  {
    origin: '汉',
    pinyin: 'hàn',
    initial: 'h',
    final: 'àn',
    first: 'h',
    finalHead: '',
    finalBody: 'à',
    finalTail: 'n',
    num: 4,
    isZh: true,
    polyphonic: ['hàn'],
    inZhRange: 'true',
    result: 'hàn',
  },
  {
    origin: '语',
    pinyin: 'yǔ',
    initial: 'y',
    final: 'ǔ',
    first: 'y',
    finalHead: '',
    finalBody: 'ǔ',
    finalTail: '',
    num: 3,
    isZh: true,
    polyphonic: ['yǔ', 'yù'],
    inZhRange: 'true',
    result: 'yǔ',
  },
  {
    origin: '拼',
    pinyin: 'pīn',
    initial: 'p',
    final: 'īn',
    first: 'p',
    finalHead: '',
    finalBody: 'ī',
    finalTail: 'n',
    num: 1,
    isZh: true,
    polyphonic: ['pīn'],
    inZhRange: 'true',
    result: 'pīn',
  },
  {
    origin: '音',
    pinyin: 'yīn',
    initial: 'y',
    final: 'īn',
    first: 'y',
    finalHead: '',
    finalBody: 'ī',
    finalTail: 'n',
    num: 1,
    isZh: true,
    polyphonic: ['yīn'],
    inZhRange: 'true',
    result: 'yīn',
  },
];
 */

Multiple

When options.multiple is true, the returned value is all Pinyins of the polyphonic character.

This only takes effect when the length of the text parameter equals 1.

javascript
import { pinyin } from 'pinyin-pro';

// Get all pinyins
pinyin('好', { multiple: true }); // 'hǎo hào'
// Get all pinyins in array
pinyin('好', { multiple: true, type: 'array' }); // ["hǎo", "hào"]
// It doesn't take effect when the length of `text` is not 1
pinyin('好学', { multiple: true }); // hào xué

Surname Mode

Set options.surname to head (to recognize surname characters only at the beginning of the string) or all (to recognize all surname characters in the string) to enable surname mode. When enabled, characters that match surnames from the "Hundred Family Surnames" will prioritize outputting the surname pinyin.

javascript
import { pinyin } from 'pinyin-pro';

// Surname mode not enabled
pinyin('我叫曾乐乐'); // 'wǒ jiào céng lè lè'

// Enable head surname mode
pinyin('我叫曾乐乐', { surname: 'head' }); // 'wǒ jiào zēng lè lè'

// Enable all surname mode (will recognize “乐” as the surname yuè of 乐毅)
pinyin('我叫曾乐乐', { surname: 'all' }); // 'wǒ jiào zēng yuè yuè'

Customize Separator

Use options.separator to customize separator between pinyins, only effective when type: 'string':

javascript
import { pinyin } from 'pinyin-pro';

pinyin('汉语拼音', { separator: '-' }); // 'hàn-yǔ-pīn-yīn'

NonZh Character

options.nonZh can configure the returned value's format of non Chinese characters.

javascript
import { pinyin } from 'pinyin-pro';

// Default non Chinese characters will be output with space intervals
pinyin('我very喜欢你'); // 'wǒ v e r y xǐ huān nǐ'

// When options.nonZh is removed, non Chinese characters in the output will be removed.
pinyin('我very喜欢你', { nonZh: 'removed' }); // 'wǒ xǐ huān nǐ'

// When options.nonZh is consecutive, non Chinese characters will be output compactly.
pinyin('我very喜欢你', { nonZh: 'consecutive' }); // 'wǒ very xǐ huān nǐ'

Replace `ü` by `v`

When options.v is true, the ü in returned value will be replaced by v. (ǖ,ǘ,ǚ,ǜ with tone won't be replaced):

javascript
import { pinyin } from 'pinyin-pro';

// ü
pinyin('吕布', { toneType: 'none' }); // lü bu
// v
pinyin('吕布', { toneType: 'none', v: true }); // lv bu
// ǖ,ǘ,ǚ,ǜ
pinyin('吕布', { v: true }); // lǚ bù
// v with tone
pinyin('吕布', { type: 'num', v: true }); // lv3 bu4

Segmentation Algorithms

Set options.segmentit to choose different segmentation algorithms. The default is the maximum probability algorithm:

javascript
import { pinyin } from 'pinyin-pro';

// Reverse Maximum Matching Algorithm: Fastest Speed
pinyin('小明硕士毕业于中国科学院计算所,后在日本京都大学深造', {
  segmentit: 1,
});

// Maximum Probability Algorithm: Most Accurate Recognition
pinyin('小明硕士毕业于中国科学院计算所,后在日本京都大学深造', {
  segmentit: 2,
});

// Minimum Segmentation Algorithm
pinyin('小明硕士毕业于中国科学院计算所,后在日本京都大学深造', {
  segmentit: 3,
});

Exclude `y` and `w` from Initial Consonants

According to wiki, y and w are not considered initial consonants, but for convenience, in pinyin-pro, y and w are considered initial consonants by default. Setting options.initialPattern to standard will exclude y and w from the initial consonants.

javascript
import { pinyin } from 'pinyin-pro';

pinyin('汉语拼音', {
  pattern: 'initial',
  initialPattern: 'standard',
  type: 'array'
}); // ['h', '', 'p', '']

API

Function

js
import { pinyin } from 'pinyin-pro';

interface BasicOptions {
    type: 'string' | 'array' | 'all';
    toneType?: 'symbol' | 'num' | 'none';
    pattern?: 'pinyin' | 'initial' | 'final' | 'num' | 'first' | 'finalHead' | 'finalBody' | 'finalTail';
    multiple?: boolean;
    removeNonZh?: boolean;
    nonZh?: 'spaced' | 'consecutive' | 'removed';
    v?: boolean;
    segmentit?: TokenizationAlgorithm; // v3.20.0+
    surname?: 'off' | 'head' | 'all'; // v3.21.0+
    mode?: 'normal' | 'surname'; // deprecated, use surname to replace
    toneSandhi?: boolean | { yi?: boolean; bu?: boolean; thirdTone?: boolean };
    nonZhScope?: RegExp; // 3.24.0+
    initialPattern?: 'standard' | 'yw'; // 3.27.0+
    traditional?: boolean; // 3.28.0+
}

enum TokenizationAlgorithm {
  ReverseMaxMatch = 1,
  MaxProbability = 2,
  MinTokenization = 3,
}

interface AllData {
    origin: string;
    pinyin: string;
    initial: string;
    final: string;
    num: number;
    first: string;
    finalHead: string;
    finalBody: string;
    finalTail: string;
    isZh: boolean;
    polyphonic: string[]; // v3.20.0+
    inZhRange: boolean; // v3.20.0+
    result: string; // v3.24.0+
}

 // 返回转换后的信息
function pinyin(text: string, options?: BasicOptions): string | string[] | AllData[]

Parameters

  • text (required):string, string that needs to be converted to pinyin
  • options (optional):object, content and format of the output. For more detailed information, please refer to the table below

Packages Docs En Docs Use Polyphonic (`packages/docs/en/docs/use/polyphonic.md`)

polyphonic

Use the polyphonic API to get all Pinyins of Chinese characters.

::: tip
In most cases, you only need to use the pinyin API, which automatically recognizes the correct pinyin of polyphonic Chinese characters in text. polyphonic is used to get all Pinyins of each Chinese characters, rather than the correct Pinyin of polyphonic Chinese words in a sentence.
:::

Example

Basic Use

Use the type attribute to control the format of the return value:

text
/* Detailed source-code truncated for AI context efficiency. */

Tone

Use the toneType attribute to control the display of tones:

js
import { polyphonic } from 'pinyin-pro';

const resultNone = polyphonic('好好学习', { toneType: 'none' }); // ['hao', 'hao', 'xue', 'xi']

const resultNum = polyphonic('好好学习', { toneType: 'num' }); // ['hao3 hao4', 'hao3 hao4', 'xue2', 'xi2']

API

The parameters of polyphonic are mostly the same as pinyin.

Function

js
import { polyphonic } from 'pinyin-pro';

interface BasicOptions {
    type: 'string' | 'array' | 'all';
    toneType?: 'symbol' | 'num' | 'none';
    pattern?: 'pinyin' | 'initial' | 'final' | 'num' | 'first' | 'finalHead' | 'finalBody' | 'finalTail';
    nonZh?: 'spaced' | 'consecutive' | 'removed';
    v?: boolean;
}

interface AllData {
    origin: string;
    pinyin: string;
    initial: string;
    final: string;
    num: number;
    first: string;
    finalHead: string;
    finalBody: string;
    finalTail: string;
    isZh: boolean;
}

 // 返回转换后的信息
function polyphonic(text: string, options?: BasicOptions): string[] | string[][] | AllData[][]

Parameters

Attribute Type Description Optional Values Detail Default Value
type string The format of returned value string string[] string
array string[][]
all AllData[][]
toneType string The display of tone symbol Normal symbol
none Hide
num Display in numbers after Pinyin
pattern string The content of returned value pinyin Full Pinyin pinyin
initial initial of Pinyin
final final of Pinyin
num Numbers of tone
first first character
finalHead head of final
finalBody body of final
finalTail tail of final
nonZh string Non Chinese Character Processing spaced Use spaces to separate spaced
consecutive consecutive
removed Remove them in returned value
v boolean Whether using v to replace ü in returned value false not replace false
true replace

Packages Docs En Docs Use Segment (`packages/docs/en/docs/use/segment.md`)

Segment

The pinyin-pro library exports a segment function for word segmentation output.

::: tip
To ensure the accuracy of word segmentation, it is necessary to first add a comprehensive dictionary, such as @pinyin-pro/data/complete or @pinyin-pro/data/modern, using the addDict API before utilizing the segment API.
:::

Example

Basic Usage

js
import { segment, addDict } from 'pinyin-pro';
import CompleteDict from '@pinyin-pro/data/complete';

addDict(CompleteDict);

const result = segment('小明硕士毕业于中国科学院计算所,后在日本京都大学深造');

// Conversion result:
[
  { origin: '小', result: 'xiǎo' },
  { origin: '明', result: 'míng' },
  { origin: '硕士', result: 'shuòshì' },
  { origin: '毕业', result: 'bìyè' },
  { origin: '于', result: 'yú' },
  { origin: '中国科学院', result: 'zhōngguókēxuéyuàn' },
  { origin: '计算所', result: 'jìsuànsuǒ' },
  { origin: ',', result: ',' },
  { origin: '后', result: 'hòu' },
  { origin: '在', result: 'zài' },
  { origin: '日本京都大学', result: 'rìběnjīngdūdàxué' },
  { origin: '深造', result: 'shēnzào' },
];

Different Output Formats

Specify different output formats using the format parameter.

AllSegment

js
import { segment, OutputFormat, addDict } from 'pinyin-pro';
import CompleteDict from '@pinyin-pro/data/complete';

addDict(CompleteDict);

const result = segment('小明硕士毕业于中国科学院计算所,后在日本京都大学深造', {
  format: OutputFormat.AllSegment,
});

// Conversion result:
[
  { origin: '小', result: 'xiǎo' },
  { origin: '明', result: 'míng' },
  { origin: '硕士', result: 'shuòshì' },
  { origin: '毕业', result: 'bìyè' },
  { origin: '于', result: 'yú' },
  { origin: '中国科学院', result: 'zhōngguókēxuéyuàn' },
  { origin: '计算所', result: 'jìsuànsuǒ' },
  { origin: ',', result: ',' },
  { origin: '后', result: 'hòu' },
  { origin: '在', result: 'zài' },
  { origin: '日本京都大学', result: 'rìběnjīngdūdàxué' },
  { origin: '深造', result: 'shēnzào' },
];

AllArray

js
import { segment, OutputFormat, addDict } from 'pinyin-pro';
import CompleteDict from '@pinyin-pro/data/complete';

addDict(CompleteDict);

const result = segment('小明硕士毕业于中国科学院计算所,后在日本京都大学深造', {
  format: OutputFormat.AllArray,
});

// Conversion result:
[
  [{ origin: '小', result: 'xiǎo' }],
  [{ origin: '明', result: 'míng' }],
  [
    { origin: '硕', result: 'shuò' },
    { origin: '士', result: 'shì' },
  ],
  [
    { origin: '毕', result: 'bì' },
    { origin: '业', result: 'yè' },
  ],
  [{ origin: '于', result: 'yú' }],
  [
    { origin: '中', result: 'zhōng' },
    { origin: '国', result: 'guó' },
    { origin: '科', result: 'kē' },
    { origin: '学', result: 'xué' },
    { origin: '院', result: 'yuàn' },
  ],
  [
    { origin: '计', result: 'jì' },
    { origin: '算', result: 'suàn' },
    { origin: '所', result: 'suǒ' },
  ],
  [{ origin: ',', result: ',' }],
  [{ origin: '后', result: 'hòu' }],
  [{ origin: '在', result: 'zài' }],
  [
    { origin: '日', result: 'rì' },
    { origin: '本', result: 'běn' },
    { origin: '京', result: 'jīng' },
    { origin: '都', result: 'dū' },
    { origin: '大', result: 'dà' },
    { origin: '学', result: 'xué' },
  ],
  [
    { origin: '深', result: 'shēn' },
    { origin: '造', result: 'zào' },
  ],
];

AllString

js
import { segment, OutputFormat, addDict } from 'pinyin-pro';
import CompleteDict from '@pinyin-pro/data/complete';

addDict(CompleteDict);

const result = segment('小明硕士毕业于中国科学院计算所,后在日本京都大学深造', {
  format: OutputFormat.AllString,
});

// Conversion result:
{
  origin: "小 明 硕士 毕业 于 中国科学院 计算所 , 后 在 日本京都大学 深造",
  result: "xiǎo míng shuòshì bìyè yú zhōngguókēxuéyuàn jìsuànsuǒ , hòu zài rìběnjīngdūdàxué shēnzào",
}

PinyinSegment

js
import { segment, OutputFormat, addDict } from 'pinyin-pro';
import CompleteDict from '@pinyin-pro/data/complete';

addDict(CompleteDict);

const result = segment('小明硕士毕业于中国科学院计算所,后在日本京都大学深造', {
  format: OutputFormat.PinyinSegment,
});

// Conversion result:
[
  'xiǎo',
  'míng',
  'shuòshì',
  'bìyè',
  'yú',
  'zhōngguókēxuéyuàn',
  'jìsuànsuǒ',
  ',',
  'hòu',
  'zài',
  'rìběnjīngdūdàxué',
  'shēnzào',
];

PinyinArray

js
import { segment, OutputFormat, addDict } from 'pinyin-pro';
import CompleteDict from '@pinyin-pro/data/complete';

addDict(CompleteDict);

const result = segment('小明硕士毕业于中国科学院计算所,后在日本京都大学深造', {
  format: OutputFormat.PinyinArray,
});

// Conversion result:
[
  ['xiǎo'],
  ['míng'],
  ['shuò', 'shì'],
  ['bì', 'yè'],
  ['yú'],
  ['zhōng', 'guó', 'kē', 'xué', 'yuàn'],
  ['jì', 'suàn', 'suǒ'],
  [','],
  ['hòu'],
  ['zài'],
  ['rì', 'běn', 'jīng', 'dū', 'dà', 'xué'],
  ['shēn', 'zào'],
];

PinyinString

js
import { segment, OutputFormat, addDict } from 'pinyin-pro';
import CompleteDict from '@pinyin-pro/data/complete';

addDict(CompleteDict);

const result = segment('小明硕士毕业于中国科学院计算所,后在日本京都大学深造', {
  format: OutputFormat.PinyinString,
});

// Conversion result:
('xiǎo míng shuòshì bìyè yú zhōngguókēxuéyuàn jìsuànsuǒ , hòu zài rìběnjīngdūdàxué shēnzào');

ZhSegment

js
import { segment, OutputFormat, addDict } from 'pinyin-pro';
import CompleteDict from '@pinyin-pro/data/complete';

addDict(CompleteDict);

const result = segment('小明硕士毕业于中国科学院计算所,后在日本京都大学深造', {
  format: OutputFormat.ZhSegment,
});

// Conversion result:
[
  '小',
  '明',
  '硕士',
  '毕业',
  '于',
  '中国科学院',
  '计算所',
  ',',
  '后',
  '在',
  '日本京都大学',
  '深造',
];

ZhArray

js
import { segment, OutputFormat, addDict } from 'pinyin-pro';
import CompleteDict from '@pinyin-pro/data/complete';

addDict(CompleteDict);

const result = segment('小明硕士毕业于中国科学院计算所,后在日本京都大学深造', {
  format: OutputFormat.ZhArray,
});

// Conversion result:
[
  ['小'],
  ['明'],
  ['硕', '士'],
  ['毕', '业'],
  ['于'],
  ['中', '国', '科', '学', '院'],
  ['计', '算', '所'],
  [','],
  ['后'],
  ['在'],
  ['日', '本', '京', '都', '大', '学'],
  ['深', '造'],
];

ZhString

js
import { segment, OutputFormat, addDict } from 'pinyin-pro';
import CompleteDict from '@pinyin-pro/data/complete';

addDict(CompleteDict);

const result = segment('小明硕士毕业于中国科学院计算所,后在日本京都大学深造', {
  format: OutputFormat.ZhString,
});

// Conversion result:
('小 明 硕士 毕业 于 中国科学院 计算所 , 后 在 日本京都大学 深造');

Custom Separator

Customize the separator using the separator parameter. This only applies to the AllString, PinyinString, and ZhString output formats.

js
import { segment, OutputFormat, addDict } from 'pinyin-pro';
import CompleteDict from '@pinyin-pro/data/complete';

addDict(CompleteDict);

const result = segment('小明硕士毕业于中国科学院计算所,后在日本京都大学深造', {
  format: OutputFormat.AllString,
  separator: '/',
});

// Conversion result:
{
  origin: "小/明/硕士/毕业/于/中国科学院/计算所/,/后/在/日本京都大学/深造",
  result:
    "xiǎo/míng/shuòshì/bìyè/yú/zhōngguókēxuéyuàn/jìsuànsuǒ/,/hòu/zài/rìběnjīngdūdàxué/shēnzào",
}

Syntax and Parameters

Except for the format and separator parameters, the functions of the other parameters are the same as those in the pinyin API.

ts
import { segment, OutputFormat } from 'pinyin-pro';

interface SegmentOptions {
  toneType?: 'symbol' | 'num' | 'none';
  removeNonZh?: boolean;
  nonZh?: 'spaced' | 'consecutive' | 'removed';
  v?: boolean;
  segmentit?: TokenizationAlgorithm;
  surname?: 'off' | 'head' | 'all';
  mode?: 'normal' | 'surname';
  toneSandhi?: boolean | { yi?: boolean; bu?: boolean; thirdTone?: boolean };
  nonZhScope?: RegExp;
  separator?: string;
  format?: OutputFormat;
  initialPattern?: 'standard' | 'yw'; // 3.27.0+
  traditional?: boolean; // 3.28.0+
}

function segment(text: string, options?: SegmentOptions);

Packages Docs En Docs Use Traditional (`packages/docs/en/docs/use/traditional.md`)

addTraditionalDict

pinyin-pro exports the addTraditionalDict function, which is used to better recognize traditional Chinese characters.

::: tip
You need to install @pinyin-pro/data to import the traditional character mapping table

bash
npm install @pinyin-pro/data

:::

Examples

`pinyin`

js
import { pinyin, addTraditionalDict } from 'pinyin-pro';
import TraditionalDict from '@pinyin-pro/data/traditional';

// Before using addTraditionalDict
const result1 = pinyin('一个轉盤'); // Result: yī gè zhuǎn pán

// After using addTraditionalDict
addTraditionalDict(TraditionalDict);
const result2 = pinyin('一个轉盤', { traditional: true }); // Result: yī gè zhuàn pán

`html`

text
/* Detailed source-code truncated for AI context efficiency. */

`segment`

js
import { segment, addTraditionalDict } from 'pinyin-pro';
import TraditionalDict from '@pinyin-pro/data/traditional';

// Before using addTraditionalDict
const result1 = segment('一个轉盤');
/*
[
  { "origin": "一", "result": "yí" },
  { "origin": "个", "result": "gè" },
  { "origin": "轉", "result": "zhuǎn" },
  { "origin": "盤", "result": "pán" }
]
*/

// After using addTraditionalDict
addTraditionalDict(TraditionalDict);
const result2 = segment('一个轉盤', { traditional: true });
/*
[
  { "origin": "一", "result": "yí" },
  { "origin": "个", "result": "gè" },
  { "origin": "轉", "result": "zhuàn" },
  { "origin": "盤", "result": "pán" }
]
*/

Syntax and Parameters

Receives a traditional and simplified character mapping table object as a parameter.

ts
import { addTraditionalDict } from 'pinyin-pro';

function addTraditionalDict(dict: Record<string, string>);

// dict 示例
const Dict = {
  "萬": "万",
  "與": "与",
  "醜": "丑",
  "專": "专",
  "業": "业",
  "東": "东",
  "絲": "丝",
  "丟": "丢",
  "兩": "两",
}

Packages Docs Zh Docs Guide Api Size (`packages/docs/zh/docs/guide/api-size.md`)

API Size

以下数据由 pnpm size 自动生成。ESM 各 API 为独立打包并开启 Tree Shaking 后的压缩体积;UMD 不支持按 API Tree Shaking,展示完整产物体积。括号内为对应产物 gzip 后的体积。

API ESM UMD
pinyin 307.03 KB (gzip 134.83 KB) 317.47 KB (gzip 138.33 KB)
segment 305.79 KB (gzip 134.04 KB)
match 185.67 KB (gzip 80.90 KB)
convert 1.78 KB (gzip 0.98 KB)
html 307.87 KB (gzip 135.13 KB)
polyphonic 180.75 KB (gzip 78.83 KB)
总体积 561.18 KB (gzip 158.13 KB)

Packages Docs Zh Docs Guide Changelog (`packages/docs/zh/docs/guide/changelog.md`)

更新日志

3.29.5

  • 【feat】支持连续三声变调,可通过 toneSandhi.thirdTone 开启,同时保持原有 toneSandhi 布尔值的兼容语义 #356
  • 【perf】match: 使用回溯指针重建匹配路径,减少匹配过程中的数组分配 #367
  • 【perf】match: 优化前缀匹配逻辑,减少不必要的字符串处理 #369
  • 【perf】polyphonic: 复用 final 解析结果,减少 type: 'all' 模式下的重复计算 #372
  • 【perf】match: 复用已拆分的文本字符,避免重复分割 #373
  • 【perf】优化 AC 自动机构建过程中的节点查找和队列处理 #374
  • 【perf】合并连续的自定义拼音更新,减少自定义词典的重复构建 #375

3.29.4

  • 【fix】兼容 Cloudflare Workers 等运行时在模块初始化阶段禁用定时器的限制 #364
  • 【perf】match: 优化 DP 过程中的重复计算以及内存占用 #362、#360
  • 【perf】segmentit: Node 环境下不再通过 setTimeout 预构建 AC 自动机,进一步降低 import 开销 #361

3.29.3

感谢 @luojiyin1987 对分词模块的持续优化,pinyin API 性能进一步提升(约 20%+):

  • 【perf】segmentit: 构建 AC 自动机时避免 prefix 字符串分配 #344
  • 【perf】segmentit: 复用 AC 匹配过程中的子节点查找 #346
  • 【perf】segmentit: 使用回溯指针重建最大概率路径 #348
  • 【perf】splitString: 对 BMP 文本走原生 split 快路径 #349
  • 【perf】pinyin: 文本不含 々 时跳过叠字处理器 #351

3.29.2

感谢 @luojiyin1987 的一系列优化,pinyin API 性能得到显著提升(约30%+):

  • 【perf】pinyin: 在所有输出模式中复用解析后的 final #342
  • 【fix】customPinyin: 防止更新时 pattern 重复积累 #340
  • 【perf】pinyin: 在多个 middleware 中复用分割后的字符 #338
  • 【perf】pinyin: 避免非多音字拼音被 split 分割 #336

3.29.1

  • 【perf】推迟 AC 自动机的构建时机,减少 import pinyin-pro 时对主线程的阻塞 #333
  • 【perf】优化 middlewareMultiple 重复计算的问题 #330
  • 【fix】修复 nonZhScope 非中文字符移除不彻底的问题 #329

3.29.0

  • 【perf】优化 match API 在 ESM 模式下 tree shaking 的 size,306.81 KB (gzip 134.49 KB) > 185.44 KB (gzip 80.79 KB) #323
  • 【perf】优化 ESM 打包配置,确保 tree shaking 时仅引入必要代码,减小各个 API 的 size #327

3.28.2

  • 【patch】词库修正以下词语:

    diff
    行长: 'háng cháng', // [!code --]
    行长: 'háng zhǎng', // [!code ++]

3.28.1

  • 【feat】convert api 中增加了对于儿化音缩写格式的识别支持 #306

3.28.0

  • 【feat】新增 addTraditionalDict API,用于更好的识别繁体字 #303

3.27.0

  • 【feat】pinyin API 新增 initialPattern 选项,用于排除 y 和 w 作为声母 #295

3.26.0

  • 【feat】修复 first 在 pattern: 'first' 模式和 type: 'all' 中返回值不一致的问题:修改为对于非中文,统一返回原始非中文字符 #278

3.25.0

  • 【feat】match API 新增 v 选项,允许使用 v 匹配 ü 的拼音 #276

3.24.2

  • 【feat】html API 增加 rp 选项,用于去除输出结果中的 <rp>(</rp> 和 <rp>)</rp> #272
  • 【feat】html API 中自定义类名为 false 或者 null 时,保持默认类名 #271

3.24.1

  • 【fix】修复 segment 对于最后的标点符号丢弃的问题 #268

3.24.0

  • 【feat】新增 segment API 用于分词 #265
  • 【feat】pinyin API 新增 nonZhScope 属性用于指定 nonZh 的范围 #266

3.23.1

  • 【patch】修正部分读音 #260

3.23.0

  • 【feat】支持外部调用 getInitialAndFinal、getFinalParts、getNumOfTone 等 API #255

3.22.2

  • 【fix】修复 alias 导致的 .d.ts 文件报错 #253

3.22.1

  • 【patch】校正部分词库 #252
  • 【perf】小幅优化性能 #251

3.22.0

  • 【feat】各 api 全面适配双 unicode 编码中文字符 #242、#243、#247
  • 【feat】支持《通用汉字规范表》 中所有字符 #244
  • 【feat】支持叠字符 々 的发音 #245
  • 【feat】支持 êê̄ếê̌ề 等拼音字符 #248
  • 【patch】修正 曲 默认读音: #249

3.21.1

  • 【fix】修复 surname: 'head' 对于复姓不生效的问题

3.21.0

  • 【feat】pinyin api 新增 surname 选项,支持只识别字符串开头的姓氏

3.20.4

  • 【fix】修复 alias 导致的 ts 类型错误

3.20.3

  • 【fix】修复 convert api 对于 iu 韵母声调转换不正确的问题
  • 【patch】修复部分字词读音,详见 #232

3.20.2

  • 【fix】修复 polyphonic 和 pinyin 对非中文字符转换表现不一致的问题

3.20.1

  • 【fix】更新词典依赖版本

3.20.0

  • 【feat】支持通过 addDict api 自定义词典
  • 【feat】增加 一 和 不 的变调智能识别,可通过 toneSandhi 参数控制开启和关闭,参考: 维基百科
  • 【feat】增加 行、斗、重 前面跟数量词时的发音智能识别
  • 【feat】增加 了 在起始的发音智能识别
  • 【feat】html api 增加 customClassMap 选项用于对指定字增加自定义类名
  • 【feat】应用了新的分词算法,支持传入词典,分词更加准确
  • 【feat】all 模式新增 polyphonic 和 inZhRange 属性
  • 【fix】修复了使用 customPinyin api 时的效率低下的问题
  • 【fix】修复 multiple 和 surname 一同使用的部分问题
  • 【fix】修复 multiple 模式只有一个非中文时丢失该字符的问题
  • 【patch】校正部分词语的拼音

3.19.6

3.19.5

  • 【fix】修复非中文字符 pattern: 'first 模式下首字母获取失败的情况

3.19.4

  • 【fix】修复非中文字符在 toneType: none 参数下转换错误的问题 #156

3.19.3

3.19.2

  • 【patch】词库修正以下词语:

    diff
    止咳: 'zhǐ ké',  // [!code ++]
    咳特灵: 'ké tè líng',  // [!code ++]

3.19.1

  • 【patch】词库修正以下词语:

    diff
    那些: 'nèi xiē', // [!code --]
    皇上: 'huáng shang', // [!code --]
    太监: 'tài jiàn', // [!code --]
    审查: 'shěn zhā', // [!code --]
    只得: 'zhǐ de', // [!code --]
    哪些: 'něi xiē', // [!code --]
    一处: 'yī chǔ', // [!code --]
    大夫: 'dài fū', // [!code --]
    便宜: 'pián yí', // [!code --]
    哪个: 'něi gè', // [!code --]
    肚子: 'dǔ zi', // [!code --]
    难得: 'nán de', // [!code --]
    晓得: 'xiǎo de', // [!code --]
    寻思: 'xín sī', // [!code --]
    夺得: 'duó de', // [!code --]
    巴结: 'bā jì', // [!code --]
    了得: 'liǎo de', // [!code --]
    行家: 'háng jia', // [!code --]
    当夜: 'dàng yè', // [!code --]
    皇上: 'huáng shàng', // [!code ++]
    太监: 'tài jian', // [!code ++]
    审查: 'shěn chá', // [!code ++]
    大夫: 'dài fu', // [!code ++]
    便宜: 'pián yi', // [!code ++]
    难得: 'nán dé', // [!code ++]
    晓得: 'xiǎo dé', // [!code ++]
    寻思: 'xún si ', // [!code ++]
    夺得: 'duó dé', // [!code ++]
    巴结: 'bā jié', // [!code ++]
    了得: 'liǎo dé', // [!code ++]
    行家: 'háng jiā', // [!code ++]

3.19.0

  • 【feat】customPinyin: customPinyin 支持对 multiple 和 polyphonic 生效

3.18.6

  • 【patch】词库修正以下词语,详见 #148
  • 【fix】convert:支持 v 输入转换,例如:lv4 se4 -> lǜ sè

3.18.5

  • 【patch】词库修正以下词语

    diff
    否极泰来: 'pǐ jí tài lái', // [!code --]
    否往泰来: 'pǐ wǎng tài lái', // [!code --]
    否去泰来: 'pǐ qù tài lái', // [!code --]
    否极泰回: 'pǐ jí tài huí', // [!code --]
    泰来否往: 'tài lái pǐ wǎng', // [!code --]
    泰来否极: 'tai lái fǒu jí', // [!code --]
    唯唯否否: 'wěi wěi fǒu fǒu', // [!code --]
    臧否: 'zāng pǐ', // [!code ++]
    否泰: 'pǐ tài', // [!code ++]
    否极泰: 'pǐ jí tài', // [!code ++]
    泰来否: 'tài lái pǐ', // [!code ++]

3.18.4

  • 【patch】词库修正以下词语

    text
    只争朝夕: 'zhǐ zhēng zhāo xī', // [!code --]
    娉婷婀娜: 'pīng tíng ē nà', // [!code --]
    鸣凤朝阳: 'míng fèng zhāo yáng', // [!code --]
    凤鸣朝阳: 'fèng míng zhāo yáng', // [!code --]
    朝阳鸣凤: 'zhāo yáng míng fèng', // [!code --]
    朝成暮徧: 'cháo chéng mù shí', // [!code --]
    朝霞: 'zhāo xiá', // [!code ++]
    朝夕: 'zhāo xī', // [!code ++]
    朝气: 'zhāo qì', // [!code ++]
    翅膀: 'chì bǎng', // [!code ++]
    省长: 'shěng zhǎng', // [!code ++]
    一担水: 'yī dàn shuǐ', // [!code ++]

3.18.3

  • 【patch】词库修正及添加以下词语:
    • 衒玉贾石: zuì yù jiǎ shí -> zuì yù gǔ shí
    • 了却: liǎo què
    • 力气: lì qi
    • 席子: xí zi
    • 林子: lín zi

3.18.2

  • 【patch】词库修正及添加以下词语:
    • 瓶子: shàn zi-> píng zi
    • 镜子: jìng zi
    • 银子: yín zi
    • 盘子: pán zi

3.18.1

  • 【fix】修复 3.18.0 因打包工具迁移导致部分 vue-cli 项目中打包失败的问题

3.18.0

  • 【feat】match:options 参数新增 insensitive 选项用于指定匹配时是否大小写不敏感,默认为 true
  • 【patch】词库添加以下词语:
    • 琵琶: pí pa
    • 蘑菇: mó gu
    • 葫芦: hú lu
    • 狐狸: hú li
    • 桔子: jú zi
    • 盒子: hé zi
    • 桌子: zhuō zi
    • 竹子: zhú zi
    • 师傅: shī fu
    • 衣服: yī fu
    • 袜子: wà zi
    • 杯子: bēi zi
    • 刺猬: cì wei
    • 麦子: mài zi
    • 队伍: duì wu
    • 知了: zhī liao
    • 鱼儿: yú er
    • 馄饨: hún tun
    • 灯笼: dēng long
    • 庄稼: zhuāng jia
    • 聪明: cōng ming

3.17.0

  • 【feat】新增 convert API,用于拼音格式转换

3.16.7

  • 【patch】词库添加以下词语:
    • 成都: chéng dū
    • 都城: dū chéng
    • 六安: lù ān
    • 蚌埠: bèng bù
    • 崆峒: kōng tóng
    • 都江堰: dū jiāng yàn

3.16.6

  • 【patch】词库添加以下词语:
    • 嘴巴: 'zuǐ ba',
    • 耳朵: 'ěr duo',
    • 茄子: 'qié zi',

3.16.5

  • 【patch】亲戚称谓及"子"相关读音校正,详见863c2e9

3.16.4

  • 【patch】词库添加以下词语:
    • 重启: chóng qǐ

3.16.3

  • 【optimize】优化初始化 AC 自动机的构建时间

3.16.2

  • 【patch】姓氏模式增加读音:
    • 肖: xiāo

3.16.1

  • 【patch】校正部分汉字及词汇的拼音以下汉字读音:

    • 苹: pín -> píng

3.16.0

  • 【feature】pinyin api 新增 separator 参数,用于支持拼音之间自定义分隔符(仅当 type: 'string' 时生效)

3.15.4

  • 【optimize】 esm 打包取消压缩混淆,解决 tree-shaking 使用失效问题

3.15.3

  • 【fix】 解决 rollup 打包后的 .d.ts 文件依然保留 alias 路径引用问题

3.15.2

  • 【fix】 优化 esm 打包格式,解决部分 node 环境中引用报错问题

3.15.1

  • 【fix】 修复 package.json 文件中 types 路径指向错误问题

3.15.0

  • 【feat】 新增 html API,用于获取带拼音汉字的 HTML 字符串
  • 【feat】 新增 polyphonic API,用于汉字的全部读音
  • 【feat】 重写 match API,增加参数控制匹配规则
  • 【patch】校正部分汉字及词汇的拼音:
    • 屏: bīng píng bǐng -> píng bǐng bīng
    • 呒: ḿ -> fǔ ḿ
    • 吋: cùn yīngcùn -> cùn dòu
    • 呎: chǐ yīngchǐ -> chǐ
    • 蝊: uu -> dìng
    • 噷: hm hěn xīn hèn -> xīn hěn hèn
    • 唡: liǎng yīngliǎng -> liǎng
    • 曢: uu -> liǎo
    • 呣: ḿ m̀ -> ḿ m̀ móu
    • 聁: uu -> pàn
    • 闧: uu -> tā
    • 屗: uu -> wěi
    • 虲: uu -> xiā
    • 屏气吞声: píng qì tūn shēng -> bǐng qì tūn shēng
    • 敛声屏息: liǎn shēng píng xī -> liǎn shēng bǐng xī
    • 删除以下字词:
      • 瓸: 'bǎiwǎ'
    • 增加以下词语:
      • 好好: hǎo hǎo

3.14.0

  • 【refactor】使用 AC 自动机算法优化拼音匹配速度,性能提升近 50 倍!
  • 【patch】校正部分汉字及词汇的拼音:
    • 种: zhòng zhǒng chóng -> zhǒng zhòng chóng
    • 去掉 种(zhǒng) 相关的多余词语
    • 增加以下词语:
      • 耕种: gēng zhòng
      • 种地: zhòng dì
      • 种菜: zhòng cài
      • 栽种: zāi zhòng
      • 接种: jiē zhòng
      • 垦种: kěn zhòng
      • 种殖: zhòng zhí
      • 种瓜: zhòng guā
      • 种豆: zhòng dòu
      • 种树: zhòng shù
      • 睡着: shuì zháo
      • 笼子: lóng zi
      • 厦门: xià mén
      • 东莞: dōng guǎn

3.13.2

  • 【patch】修正部分读音
    • 皇甫: huáng pǔ -> huáng fǔ
    • 一丁点儿: yī dīng diǎnr -> yī dīng diǎn er

3.13.1

  • 【fix】pinyin:修复 options 参数 multiple 与 surname 同时使用时冲突问题
  • 【patch】修正部分儿化字读音

3.13.0

  • 【fix】pinyin:修复 options 参数 multiple: true 和 toneType: 'none' 同时使用时,可能存在重复拼音的问题

3.12.0

  • 【feat】pinyin:options.pattern 参数新增可选值获取韵头(finalHead)、韵腹(finalBody)、韵尾(finalTail)的功能。 去看看
  • 【feat】pinyin:options.type 参数新增可选值 all 获取拼音相关完整的信息。 去看看
  • 【fix】pinyin:修复 text 参数中包含空格且 options.type 参数为 array 时输出结果错误的问题

3.11.0

  • 【perf】优化拼音词库,提升拼音识别准确率
  • 【perf】包体积优化约 10%
  • 【feat】match:新增支持中文匹配、中文及拼音混合匹配

3.10.2

  • 【patch】修正部分读音:
    • 责: zhài -> zé zhài
    • 朝阳: zhāo cháo yáng -> cháo yáng
    • 假发: jiǎ fā -> jiǎ fà
  • 【perf】优化 typescript 提示

3.10.1

  • 【patch】修正部分读音:
    • 哼: hng -> hēng hng

3.10.0

  • 【perf】包体积优化约 30%

3.9.0

  • 【feat】pinyin:options 参数增加 v 可选属性,options.v = true 可将拼音中的 ü 替换为 v。去看看

3.8.3

  • 【patch】修正部分读音:
    • 查岗: zhā gǎng -> chá gǎng
    • 查核: zhā hé -> chá hé
    • 查缉: zhā jī -> chá jī
    • 查检: zhā jiǎn -> chá jiǎn
    • 查看: zhā kàn -> chá kàn
    • 查勤: zhā qín -> chá qín
    • 查帐: zhā zhàng -> chá zhàng
    • 查照: zhā zhào -> chá zhào

3.8.2

  • 【fix】pinyin:再次修复双字节 unicode 编码的文字返回默认值不正确的问题

3.8.1

  • 【fix】pinyin:修复双字节 unicode 编码的文字返回默认值不正确的问题

3.8.0

  • 【feat】pinyin:options 参数新增 nonZh 可选属性,用于配置非中文字符串的输出规则。去看看

3.7.2

  • 【patch】修正部分读音:
    • 物美价廉: jià lián wù měi -> wù měi jià lián

3.7.1

  • 【fix】pinyin:修复 “嗯” 在 options.toneType = none 时拼音转换错误的问题

3.7.0

  • 【perf】支持 esm 动态引入

3.6.2

  • 【fix】pinyin:修复 customPinyin API 和 options.mode = surname 同时使用时没有优先匹配自定义拼音的问题
  • 【fix】pinyin:修复部分姓氏拼音不正确的问题

3.6.1

  • 【fix】pinyin:修复 options.removeNonZh = true 且输入字符串全部为非汉字时的内存溢出问题

3.6.0

  • 【feat】pinyin:options 参数新增 removeNonZh 可选属性,为 options.removeNonZh = true 时移除非汉字的字符

3.5.0

  • 【feat】新增 match api 以支持拼音文本匹配功能。去看看

3.4.1

  • 【fix】pinyin:修复 options.pattern = 'first' 或者 options.pattern = 'initial' 时,指定 options.toneType = 'num' 获取音调失效的问题

3.4.0

  • 【feat】pinyin:options 参数新增 mode 可选属性,options.mode = 'surname' 模式支持姓氏模式拼音识别。去看看
  • 【feat】新增 customPinyin api,支持用户自定义拼音功能。去看看
  • 【fix】修复文本过长时堆栈溢出问题
  • 【patch】修正部分读音:
    • 褚: zhǔ -> chǔ zhǔ
    • 俞: yù -> yú yù
    • 臧: zàng -> zāng
    • 贲: bì -> bēn bì
    • 莘: xīn -> shēn xīn
    • 郦: zhí -> lì zhí

3.3.1

  • 【fix】修复文本过长时堆栈溢出问题

3.3.0

  • 【perf】优化拼音转换速度,提升近 30 倍!

3.2.3

  • 【perf】优化 typescript 提示
  • 【perf】优化拼音转换算法,提高转换速度

3.2.2

  • 【fix】pinyin:修复 options 为 { multiple: true, type: 'array' } 时若未找到多音字结果的报错问题

3.2.1

  • 【patch】修复部分读音
    • 艾: yì -> ài yì
    • 吽: ōu -> hōng hǒu ōu

3.2.0

  • 【perf】根据单字的使用频率调整字典顺序以提升性能,长句的转换时间只需之前版本 50% 左右的时间
  • 【patch】修复部分读音:
    • 啊: ā -> a
    • 阿: ē -> ā
  • 【perf】支持 <script /> 链接使用

3.1.0

  • 【feat】pinyin:options.pattern 新增 first 可选值获取拼音首字母
  • 【docs】修复 readme 中音调形式参数 toneType 错写成了 tone 的错误

3.0.7

  • 【perf】package.json 中去掉 readme 选项

3.0.6

  • 【docs】修复 readme 中版本更新文档链接错误问题

3.0.5

  • 【docs】优化 README.md 文档二维码大小

3.0.4

  • 【docs】README.md 增加二维码

3.0.3

  • 【lint】增加 eslintrc 规范代码质量

3.0.2

  • 【perf】优化 npm 包质量和 README.md

3.0.1

  • 【fix】修复没有 index.d.ts 类型指向的问题

3.0.0

  • 【refactor】使用 typescript + rollup 重构了项目

Packages Docs Zh Docs Guide Compare (`packages/docs/zh/docs/guide/compare.md`)

介绍

pinyin-pro 是一个专业的 JavaScript 中文转拼音的库,具备多音字识别准确、体积轻量、性能优异、功能丰富等特点。

在同类产品中,pinyin-pro 无论是多音字识别准确率、体积、性能还是功能的支持度上,都做到了全网领先。以下是关于性能及准确率方面和同类竞品 pinyin、@napi-rs/pinyin 的具体对比数据。

测试环境

  • 设备:
    • 品牌及型号:联想小新 Pro 13 ARE 2020
    • 系统:Windows10
    • RAM:16 GB
    • CPU: AMD Ryzen 7 4800U 1.8GHz
  • 运行环境: Nodejs v18.12.1

对比结果

对比项 pinyin @napi-rs/pinyin pinyin-pro
准确率 😕 Node 版: 94.097% 😕 94.097% 🤩 99.846%
😕 Web 版: 91.170%
性能 首次使用字典初始化时长 🚀 14.261ms 🐢 160.769ms 🚀 8.412ms
10k字转换耗时 🚲 74.442ms 🚀 4.298ms 🚀 7.216ms
100k字转换耗时 🐢 6287.332ms 🚀 29.32ms 🚀 45.471ms
1m字转换耗时 ⛔ 内存溢出转换失败 🚀 297.41ms 🚀 328.338ms
10m字转换耗时 ⛔ 内存溢出转换失败 🚀 3907.278ms 🚀 3375.192ms
兼容性 Web 环境 ✔️ 支持 ❌ 不支持 ✔️ 支持
Node 环境 ✔️ 支持 ✔️ 支持 ✔️ 支持

基准数据

  • 准确率测试数据可见: accuracy
  • 性能测试数据可见:speed

Packages Docs Zh Docs Guide Start (`packages/docs/zh/docs/guide/start.md`)

快速开始

环境

pinyin-pro 支持在浏览器和 Nodejs 环境运行。

安装

pinyin-pro 支持使用包管理器安装或者通过 <script />链接引入。

使用包管理器

推荐使用包管理器进行安装:

perl
# 选择一个你喜欢的包管理器

# NPM
$ npm install pinyin-pro --save

# Yarn
$ yarn add pinyin-pro

# pnpm
$ pnpm install pinyin-pro

Script 链接

也可以通过浏览器的 script 标签导入 CDN 文件使用,下面以 unpkg 和 jsDelivr CDN 厂商为例:

unpkg

html
<head>
  <script src="https://unpkg.com/[email protected]/dist/index.js"></script>
</head>


<head>
  <script src="https://unpkg.com/pinyin-pro"></script>
</head>

jsDelivr

html
<head>
  <script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/index.js"></script>
</head>


<head>
  <script src="https://cdn.jsdelivr.net/npm/pinyin-pro"></script>
</head>

::: tip
我们建议使用 CDN 引入 pinyin-pro 的用户在链接地址上锁定版本,以固定版本的方式引入,以免将来 pinyin-pro 升级时受到非兼容性更新的影响。如果你有自己的 CDN,也建议将 pinyin-pro 文件下载下来托管到你自己的 CDN 上,以免第三方 CDN 不稳定带来的影响。
:::

使用

支持多种环境及模块化规范的使用方式。

ESM

js
import { pinyin } from 'pinyin-pro';

pinyin('汉语拼音'); // 'hàn yǔ pīn yīn'

动态导入

js
import('pinyin-pro').then((exports) => {
  exports.pinyin('汉语拼音'); // 'hàn yǔ pīn yīn'
});

Script 连接

当你使用 <script /> 引入 pinyin-pro 时,会在全局(window)挂载一个名为 pinyinPro 变量。

html
<script src="https://unpkg.com/pinyin-pro"></script>

<script>
  var { pinyin } = pinyinPro;
  pinyin('汉语拼音'); // 'hàn yǔ pīn yīn'
</script>

CommonJS

js
const { pinyin } = require('pinyin-pro');

pinyin('汉语拼音'); // 'hàn yǔ pīn yīn'

Packages Docs Zh Docs More Contact (`packages/docs/zh/docs/more/contact.md`)

交流

任何使用问题可以加入 QQ 群 1042725850 或者添加作者微信 zhoulx1688888 进行咨询与反馈:


Packages Docs Zh Docs Run Run (`packages/docs/zh/docs/run/run.md`)

在线运行

已自动从 pinyin-pro 中引入 pinyin、match、html、polyphonic 和 customPinyin 等 API,无需手动引入。


Packages Docs Zh Docs Use AddDict (`packages/docs/zh/docs/use/addDict.md`)

addDict

pinyin-pro 内置了一些高频常用词的词典,想要保证高准确率,需要应用更完备的词典,可以通过 addDict 添加词典。详见 @pinyin-pro/data。

通过 npm install @pinyin-pro/data 进行安装。

示例

使用内置词典(默认)

默认词典词汇数量较少,例如不包含 日本京都大学,会导致 都 的读音识别错误:

js
import { pinyin } from 'pinyin-pro';

const result1 = pinyin('小明硕士毕业于中国科学院计算所,后在日本京都大学深造');
// 结果: xiǎo míng shuò shì bì yè yú zhōng guó kē xué yuàn jì suàn suǒ , hòu zài rì běn jīng dōu dà xué shēn zào

使用现代汉语词典

包含 日本京都大学,可以识别准确(gzip 压缩后大概 0.6MB,根据自己的需求决定是否使用):

js
import { pinyin, addDict } from 'pinyin-pro';
// 引入前需要先通过 `npm install @pinyin-pro/data` 进行安装
import ModernChineseDict from '@pinyin-pro/data/modern';

addDict(ModernChineseDict);

const result = pinyin('小明硕士毕业于中国科学院计算所,后在日本京都大学深造');
// 结果: 结果: xiǎo míng shuò shì bì yè yú zhōng guó kē xué yuàn jì suàn suǒ , hòu zài rì běn jīng dū dà xué shēn zào

使用完整词典

包含词语更多,识别率更加准确(gzip 压缩后大概 3.99MB,根据自己的需求决定是否使用):

js
import { pinyin, addDict } from 'pinyin-pro';
// 引入前需要先通过 `npm install @pinyin-pro/data` 进行安装
import CompleteDict from '@pinyin-pro/data/complete';

addDict(CompleteDict);

const result = pinyin('小明硕士毕业于中国科学院计算所,后在日本京都大学深造');
// 结果: 结果: xiǎo míng shuò shì bì yè yú zhōng guó kē xué yuàn jì suàn suǒ , hòu zài rì běn jīng dū dà xué shēn zào

语法及参数

语法

ts
import { addDict } from 'pinyin-pro';

type DICT = {
  [key: string]:
    | string // 拼音
    | [string] // [拼音]
    | [string, number] // [拼音, 词频概率]
    | [string, number, string]; // [拼音, 词频概率, 词性]
};

function addDict(dict: DICT | {}, name?: string): void;

参数

  • dict (必传):词典。
  • name (可选):词典名称。

Packages Docs Zh Docs Use Convert (`packages/docs/zh/docs/use/convert.md`)

convert

pinyin-pro 内部导出了 convert 函数,可以将拼音的格式进行转换,并返回转换后的拼音。

示例

不同格式转换

支持 numToSymbol、symbolToNum、toneNone 等转换形式:

js
import { convert } from 'pinyin-pro';

// 数组转符号(numToSymbol)
convert('pin1 yin1'); // 'pīn yīn'

// 符号转数字(symbolToNum)
convert('pīn yīn', { format: 'symbolToNum' }); // 'pin1 yin1'

// 消除符号(toneNone)
convert('pīn yīn', { format: 'toneNone' }); // 'pin yin'
convert('pin1 yin1', { format: 'toneNone' }); // 'pin yin'

数组格式

支持输入为数组格式,转换后也返回数组格式:

js
import { convert } from 'pinyin-pro';

convert(['pin1', 'yin1']); // ['pīn', 'yīn']

自定义分隔符

输入为字符串格式时,可以通过 separator 参数指定分隔符:

js
import { convert } from 'pinyin-pro';

convert('pin1-yin1', { separator: '-' }); // 'pīn-yīn'

语法及参数

语法

js
import { convert } from 'pinyin-pro';

interface ConvertOptions {
  /**
   * @description 拼音之间的分隔符,默认为空格,convert方法会以该分隔符分割拼音进行转换
   */
  separator?: string;
  /**
   * @description 转换的格式, 默认为 numToSymbol
   * @example numToSymbol: pin yin -> pīn yīn
   * @example symbolToNum: pīn yīn -> pin yin
   * @example toneNone: pīn yīn -> pin yin
   */
  format?: ConvertFormat;
}

function convert(pinyin: string | string[], options?: ConvertOptions): string | string[];

参数

  • pinyin (必传):string 或 string[] 类型,要转换的拼音字符串或者拼音字符串数组
  • options (可选): object 类型,转换规则的配置,详细见下表:
属性 类型 描述 可选值 说明 默认值
separator string 指定的分隔符 - convert 方法会以该分隔符分割拼音进行转换 ' '
format string 转换的格式 numToSymbol 将拼音数字转换为带符号的拼音 numToSymbol
SymbolToNum 将带符号的拼音转换为拼音数字
toneNone 将带符号的拼音转换为无符号拼音

Packages Docs Zh Docs Use CustomPinyin (`packages/docs/zh/docs/use/customPinyin.md`)

customPinyin

pinyin-pro 内部导出了 customPinyin 方法,支持用户自定义设置词句拼音,当中文中匹配用户自己定义的词句拼音时,优先使用用户自定义的拼音。

示例

不使用自定义拼音

涉及到多音字时,部分复杂拼音或者人名等,可能识别不准确,例如你有个人名叫 张会(zhāng kuài)

js
import { pinyin } from 'pinyin-pro';

pinyin('他叫张会'); // 'tā jiào zhāng huì'

使用自定义拼音

使用 customPinyin 方法,可以让你自己补充这部分识别不准确的拼音。

js
import { pinyin, customPinyin } from 'pinyin-pro';

customPinyin({
  张会: 'zhāng kuài',
});

pinyin('他叫张会'); // 'tā jiào zhāng kuài'

对 multiple 和 polyphonic 生效

通过在 customPinyin 的第二个参数中追加 multiple 和 polyphonic,可以使其对 multiple 和 polyphonic 生效。

当 multiple 或 polyphonic 的值为 add 时,字的拼音会在原基础上追加;为 replace 时,会直接覆盖掉原基础。

js
// 追加的示例
customPinyin({
  张会: 'zhāng huài',
}, {
  multiple: 'add',
  polyphonic: 'add',
});

pinyin('张', { multiple: true }); // 'zhāng' (原先就有张,无需额外追加)
pinyin('会', { multiple: true }); // 'huì kuài huài' (将 huài 追加进去)

polyphonic('张会'); // ["zhāng", "huì kuài huài"]
js
// 替换的示例
customPinyin({
  张会: 'zhāng huài',
}, {
  multiple: 'replace',
  polyphonic: 'replace',
});

pinyin('张', { multiple: true }); // 'zhāng' (替换为 zhāng)
pinyin('会', { multiple: true }); // 'huài' (替换为 huài)

polyphonic('张会'); // ["zhāng", "huài"]

清除原自定义的数据

默认情况下,多次调用 customPinyin 补充的数据会累积叠加,可以调用 clearCustomDict 对原数据进行清除。

js
import { clearCustomDict } from 'pinyin-pro';

// 清除 pinyin api 自定义的数据
clearCustomDict('pinyin');
// 清除 pinyin api multiple 模式自定义的数据
clearCustomDict('multiple');
// 清除 polyphonic api 自定义的数据
clearCustomDict('polyphonic');
// 全部清除
clearCustomDict(['pinyin', 'multiple', 'polyphonic']);

语法及参数

语法

ts
import { customPinyin, clearCustomDict } from 'pinyin-pro';

interface PinyinMap {
  [key: string]: string;
}

type CustomHandleType = 'add' | 'replace';

type CustomDictType = 'pinyin' | 'multiple' | 'polyphonic';

interface CustomPinyinOptions {
  multiple?: CustomHandleType;
  polyphonic?: CustomHandleType;
}

function customPinyin(map: PinyinMap, options?: CustomPinyinOptions);

function clearCustomDict(dict: CustomDictType | CustomDictType[]);

参数

  • map (必传):object 类型,自定义的拼音映射,key 为汉字字符串,value 为拼音。
  • options (可选):object 类型,设置是否对 multiple 和 polyphonic 生效以及生效方式。

Packages Docs Zh Docs Use Html (`packages/docs/zh/docs/use/html.md`)

html

使用 html api 获取<ruby></ruby> 格式的汉字和拼音 HTML 字符串。

示例

常规使用

html api 返回值为 HTML 格式的字符串:

  • 每个汉字和拼音最外层是由一个 `` 标签包裹(可以通过 resultClass 属性自定义该标签的类名)
  • 内层是 <ruby></ruby> 标签用于展示汉字和拼音
  • 汉字部分由 `` 标签包裹(可以通过 chineseClass 属性自定义该标签的类名)
  • 拼音部分由 <rt class="py-pinyin-item"></rt> 标签包裹(可以通过 pinyinClass 属性自定义该标签的类名)
  • 默认情况下,非汉字没有标签包裹。通过设置 wrapNonChinese 属性的值为 true,非汉字部分会被 `` 标签包裹。(可以通过 nonChineseClass 属性自定义该标签的类名)
js
import { html } from 'pinyin-pro';

const htmlString = html('汉语拼音');

/*
<span class="py-result-item">
  <ruby>
    <span class="py-chinese-item">汉</span>
    <rp>(</rp>
    <rt class="py-pinyin-item">hàn</rt>
    <rp>)</rp>
  </ruby>
</span>
<span class="py-result-item">
  <ruby>
    <span class="py-chinese-item">语</span>
    <rp>(</rp>
    <rt class="py-pinyin-item">yǔ</rt>
    <rp>)</rp>
  </ruby>
</span>
<span class="py-result-item">
  <ruby>
    <span class="py-chinese-item">拼</span>
    <rp>(</rp>
    <rt class="py-pinyin-item">pīn</rt>
    <rp>)</rp>
  </ruby>
</span>
<span class="py-result-item">
  <ruby>
    <span class="py-chinese-item">音</span>
    <rp>(</rp>
    <rt class="py-pinyin-item">yīn</rt>
    <rp>)</rp>
  </ruby>
</span>
*/

上述 htmlString 字符串在浏览器中的预览效果如下:

不带音调

当设置 toneType 属性的值为 none 时,返回值中的拼音是不带音调的。

js
import { html } from 'pinyin-pro';

const htmlString = html('汉语拼音', { toneType: 'none' });

/*
<span class="py-result-item">
  <ruby>
    <span class="py-chinese-item">汉</span>
    <rp>(</rp>
    <rt class="py-pinyin-item">han</rt>
    <rp>)</rp>
  </ruby>
</span>
<span class="py-result-item">
  <ruby>
    <span class="py-chinese-item">语</span>
    <rp>(</rp>
    <rt class="py-pinyin-item">yu</rt>
    <rp>)</rp>
  </ruby>
</span>
<span class="py-result-item">
  <ruby>
    <span class="py-chinese-item">拼</span>
    <rp>(</rp>
    <rt class="py-pinyin-item">pin</rt>
    <rp>)</rp>
  </ruby>
</span>
<span class="py-result-item">
  <ruby>
    <span class="py-chinese-item">音</span>
    <rp>(</rp>
    <rt class="py-pinyin-item">yin</rt>
    <rp>)</rp>
  </ruby>
</span>
*/

上述 htmlString 字符串在浏览器中的预览效果如下:

自定义样式

可以通过 html api 返回值中的类名来控制具体的样式,如下面的例子中,我们让汉字部分为蓝色,拼音部分为红色。

js
// js
import { html } from 'pinyin-pro';

const htmlString = html('汉语拼音');
css
/* css */
.py-chinese-item {
  color: blue;
}
.py-pinyin-item {
  color: red;
}

在浏览器中的预览效果:

指定文字样式

可以通过 customClassMap 参数对于指定字符应用单独的样式。如下面的例子中,让 汉 部分为红色,音 部分为蓝色。

js
import { html } from 'pinyin-pro';

const htmlString = html('汉语拼音', {
  customClassMap: {
    'red-item': ['汉'],
    'blue-item': ['音'],
  },
});

/*
<span class="py-result-item red-item">
	<ruby>
		<span class="py-chinese-item">汉</span>
		<rp>(</rp>
		<rt class="py-pinyin-item">hàn</rt>
		<rp>)</rp>
	</ruby>
</span>
<span class="py-result-item">
	<ruby>
		<span class="py-chinese-item">语</span>
		<rp>(</rp>
		<rt class="py-pinyin-item">yǔ</rt>
		<rp>)</rp>
	</ruby>
</span>
<span class="py-result-item">
	<ruby>
		<span class="py-chinese-item">拼</span>
		<rp>(</rp>
		<rt class="py-pinyin-item">pīn</rt>
		<rp>)</rp>
	</ruby>
</span>
<span class="py-result-item blue-item">
	<ruby>
		<span class="py-chinese-item">音</span>
		<rp>(</rp>
		<rt class="py-pinyin-item">yīn</rt>
		<rp>)</rp>
	</ruby>
</span>
*/
css
/* css */
.red-item {
  color: red;
}
.blue-item {
  color: blue;
}

在浏览器中的预览效果:

语法及参数

语法

ts
import { customPinyin } from 'pinyin-pro';

interface HtmlOptions {
  resultClass?: string;
  pinyinClass?: string;
  chineseClass?: string;
  wrapNonChinese?: boolean;
  nonChineseClass?: string;
  tone?: boolean;
  rp?: boolean; // v3.24.2+  是否输出 <rp>(</rp> 和 <rp>)</rp> 标签
  toneType?: 'symbol' | 'num' | 'none';
  v?: boolean;
  segmentit?: TokenizationAlgorithm; // v3.20.0+
  surname?: 'off' | 'head' | 'all'; // v3.21.0+
  mode?: 'normal' | 'surname'; // 已废弃,使用 surname 替代
  toneSandhi?: boolean | { yi?: boolean; bu?: boolean; thirdTone?: boolean };
  initialPattern?: 'standard' | 'yw'; // 3.27.0+
  traditional?: boolean; // 3.28.0+
}

function html(text: string, options?: HtmlOptions): string {}

参数

  • text (必传): string 类型,要转换的汉字字符串。
  • options (可选): object 类型,返回值相关的配置,具体如下表:
属性 类型 描述 可选值 默认值
resultClass string 汉字和拼音最外层 &lt;span&gt; 标签的类名 - py-result-item
pinyinClass string 拼音外层 &lt;rt&gt; 标签的类名 - py-pinyin-item
chineseClass string 汉字外层 &lt;span&gt; 标签的类名 - py-chinese-item
wrapNonChinese boolean 是否用 &lt;span&gt; 标签包裹非汉字字符。如果是要对非汉字字符也做一些自定义样式处理,建议设置为 true; 如果 text 参数本身也是一个 HTML 字符串,建议设置为 false 以防止影响 text 本身的结构 true/false false
nonChineseClass string 非汉字字符外层 &lt;span&gt; 标签的类名(仅在 wrapNonChinese 值为 true 时有效) - py-non-chinese-item
toneType string 拼音中音调的显示形式 symbol/none/num symbol

Packages Docs Zh Docs Use Match (`packages/docs/zh/docs/use/match.md`)

match

pinyin-pro 内部导出了 match 函数,可以进行文字和拼音匹配,并返回匹配的文字在字符串中的下标。

示例

常规匹配

若拼音和文本匹配,返回匹配的文本下标:

js
import { match } from 'pinyin-pro';

match('汉语拼音', 'hanyupinyin'); // [0, 1, 2, 3]

是否连续

使用 continuous 属性指定匹配的汉字下标是否为连续的才算匹配成功(默认值为 false,即不需要为连续的匹配):

js
import { match } from 'pinyin-pro';

match('汉语拼音', 'hanpin'); // [0, 2]

match('汉语拼音', 'hanpin', { continuous: true }); // null

精度

使用 precision 属性可以控制汉字和拼音匹配的精度:

js
import { match } from 'pinyin-pro';

// 默认首字母匹配算匹配成功
match('中文拼音', 'zwpy'); // [0, 1, 2, 3]

// every 需要每一个字符都匹配成功
match('中文拼音', 'zwpy', { precision: 'every' }); // null
match('中文拼音', 'zhongwenpinyin', { precision: 'every' }); // [0, 1, 2, 3]

// start 只要开头任意个字母匹配就算匹配成功
match('中文拼音', 'zhwpy', { precision: 'start' }); // [0, 1, 2, 3]
match('中文拼音', 'zhwpy'); // null

// any 任意有一个字母匹配就算匹配成功
match('中文拼音', 'ongwpy', { precision: 'any' }); // [0, 1, 2, 3]
match('中文拼音', 'ongwpy'); // null

空格处理

使用 space 属性控制匹配时空格是否不参与匹配:

js
import { match } from 'pinyin-pro';

// 默认不参与匹配
match('汉语拼音', 'han yupinyin'); // [0, 1, 2, 3]

match('汉语拼音', 'han yupinyin', { space: 'preserve' }); // null

最后一个字符精度

使用 lastPrecision 属性可以控制最后一个汉字和拼音匹配的精度。默认情况下,precision 为 any 时,lastPrecision 为 any; 否则 lastPrecision 为 start。

js
import { match } from 'pinyin-pro';

// 默认情况下
match('汉语拼音', 'hanyupiny'); // [1, 2, 3, 4]

// 显式控制 lastPrecision
match('汉语拼音', 'hanyupiny', { lastPrecision: 'every' }); // null

多音字匹配

对于多音字,只要其中一个读音匹配上即算匹配成功:

js
import { match } from 'pinyin-pro';

match('会计', 'kuaiji'); // [0, 1]
match('会计', 'huiji'); // [0, 1]

使用 `v` 匹配 `ü`

通过指定 v 选项来使用 v 来匹配 ü:

js
import { match } from 'pinyin-pro';

match('吕布', 'lvbu'); // [0, 1]

语法及参数

语法

js
import { match } from 'pinyin-pro';

interface MatchOptions {
  precision?: 'first' | 'start' | 'every' | 'any';
  continuous?: boolean;
  space?: 'ignore' | 'preserve';
  lastPrecision?: 'first' | 'start' | 'every' | 'any';
  v?: boolean; // v3.25.0+
}

match(text, pinyin, options?: MatchOptions); // 匹配成功返回匹配汉字对应下标数组; 不成功返回 null

参数

  • text (必传):string 类型,要匹配的文本
  • pinyin (必传):string 类型,要匹配的拼音
  • options (可选): object 类型,匹配规则的配置,详细见下表:
属性 类型 描述 可选值 说明 默认值
precision string 匹配的精度 first 首字母或者全拼和当前拼音相等即为匹配成功 first
start 以当前拼音为开头即为匹配成功
every 全拼和当前拼音严格相等才算匹配成功
any 包含当前拼音的所有字符即为匹配成功
continuous boolean 匹配的汉字下标是否需要为连续的才算匹配成功 true 不需要 false
false 需要
space string 匹配时对于汉字和拼音中空格的处理 ignore 忽略 ignore
preserve 保留
lastPrecision string 最后一个字符匹配的精度 first 首字母或者全拼和当前拼音相等即为匹配成功 当 precision 为 any 时,lastPrecision 默认为 any;其他情况下 lastPrecision 默认为 start
start 以当前拼音为开头即为匹配成功
every 全拼和当前拼音严格相等才算匹配成功
any 包含当前拼音的所有字符即为匹配成功
v boolean 是否允许使用 v 匹配 ü true 允许使用 v 匹配 ü false
false 不允许使用 v 匹配 ü

Packages Docs Zh Docs Use Others (`packages/docs/zh/docs/use/others.md`)

pinyin

pinyin-pro 内部还导出了一些中间态处理函数供大家使用。

getInitialAndFinal

可以使用 getInitialAndFinal 获取指定拼音的声母和韵母:

js
import { getInitialAndFinal } from 'pinyin-pro';

const result = getInitialAndFinal('guang');
/* 结果为:
{
  final: 'uang',
  initial: 'g',
}
*/

getFinalParts

可以使用 getFinalParts 获取指定拼音的韵头/韵腹/韵尾:

js
import { getFinalParts } from 'pinyin-pro';

const result = getFinalParts('guang');
/* 结果为:
{
  head: "u",
  body: "a",
  tail: "ng",
}
*/

getNumOfTone

可以使用 getNumOfTone 获取指定拼音的声调对应的数字:

js
import { getNumOfTone } from 'pinyin-pro';

const result = getNumOfTone('hàn yǔ de pīn yīn');
/* 结果为:
"4 3 0 1 1"
*/

Packages Docs Zh Docs Use Pinyin (`packages/docs/zh/docs/use/pinyin.md`)

pinyin

pinyin-pro 内部导出了 pinyin 函数,可以进行拼音转换,获取相关内容。

示例

拼音

通过 options.type 参数设置,可以获得数组和字符串不同的返回格式,也可以通过 options.toneType 参数控制音调在拼音中的显示格式

js
import { pinyin } from 'pinyin-pro';

// 获取带音调拼音
pinyin('汉语拼音'); // 'hàn yǔ pīn yīn'
// 获取不带声调的拼音
pinyin('汉语拼音', { toneType: 'none' }); // 'han yu pin yin'
// 获取声调转换为数字后缀的拼音
pinyin('汉语拼音', { toneType: 'num' }); // 'han4 yu3 pin1 yin1'
// 获取数组形式带音调拼音
pinyin('汉语拼音', { type: 'array' }); // ["hàn", "yǔ", "pīn", "yīn"]
// 获取数组形式不带声调的拼音
pinyin('汉语拼音', { toneType: 'none', type: 'array' }); // ["han", "yu", "pin", "yin"]
// 获取数组形式声调转换为数字后缀的拼音
pinyin('汉语拼音', { toneType: 'num', type: 'array' }); // ["han4", "yu3", "pin1", "yin1"]

声母

设置 options.pattern 为 initial 时,返回的结果将为拼音的声母。

js
import { pinyin } from 'pinyin-pro';

// 获取声母
pinyin('汉语拼音', { pattern: 'initial' }); // 'h y p y'
// 获取数组形式声母
pinyin('汉语拼音', { pattern: 'initial', type: 'array' }); // ["h", "y", "p", "y"]

韵母

设置 options.pattern 为 final 时,返回的结果将为拼音的声母。

js
import { pinyin } from 'pinyin-pro';

// 获取带音调韵母
pinyin('汉语拼音', { pattern: 'final' }); // 'àn ǔ īn īn'
// 获取不带音调韵母
pinyin('汉语拼音', { pattern: 'final', toneType: 'none' }); // 'an u in in'
// 获取音调为数字的韵母
pinyin('汉语拼音', { pattern: 'final', toneType: 'num' }); // 'an4 u3 in1 in1'
// 获取数组形式带音调韵母
pinyin('汉语拼音', { pattern: 'final', type: 'array' }); // ["àn", "ǔ", "īn", "īn"]
// 获取数组形式不带音调韵母
pinyin('汉语拼音', { pattern: 'final', toneType: 'none', type: 'array' }); // ["an", "u", "in", "in"]
// 获取数组形式音调为数字的韵母
pinyin('汉语拼音', { pattern: 'final', toneType: 'num', type: 'array' }); // ['an4', 'u3', 'in1', 'in1']

韵头(介音)/韵腹/韵尾

设置 options.pattern 为 finalHead/finalBody/finalTail 时,返回的结果将为拼音的韵头/韵腹/韵尾。

js
import { pinyin } from 'pinyin-pro';

// 返回韵头
pinyin('村庄', { pattern: 'finalHead', type: 'array' }); // [ '', 'u' ]

// 返回韵腹
pinyin('村庄', { pattern: 'finalBody', type: 'array' }); // [ 'ū', 'ā' ]

// 返回韵尾
pinyin('村庄', { pattern: 'finalTail', type: 'array' }); // [ 'n', 'ng' ]

音调

设置 options.pattern 为 num 时,返回的结果将为拼音的音调对应的数字。

js
import { pinyin } from 'pinyin-pro';

// 获取音调
pinyin('汉语拼音', { pattern: 'num' }); // '4 3 1 1'
// 获取数组形式音调
pinyin('汉语拼音', { pattern: 'num', type: 'array' }); // ["4", "3", "1", "1"]

首字母

设置 options.pattern 为 first 时,返回的结果将为拼音的首字母。

js
import { pinyin } from 'pinyin-pro';

// 获取拼音首字母
pinyin('赵钱孙李额', { pattern: 'first' }); // 'z q s l é'
// 获取不带音调拼音首字母
pinyin('赵钱孙李额', { pattern: 'first', toneType: 'none' }); // 'z q s l e'
// 获取数组形式拼音首字母
pinyin('赵钱孙李额', { pattern: 'first', type: 'array' }); // ['z', 'q', 's', 'l', 'é']
// 获取数组形式不带音调拼音首字母
pinyin('赵钱孙李额', { pattern: 'first', toneType: 'none', type: 'array' }); // ['z', 'q', 's', 'l', 'e']

完整内容

设置 options.type 为 all 时,返回的结果将为拼音的全部内容的数组。

js
const result = pinyin('汉语拼音', { type: 'all' });

/**
[
  {
    origin: '汉',
    pinyin: 'hàn',
    initial: 'h',
    final: 'àn',
    first: 'h',
    finalHead: '',
    finalBody: 'à',
    finalTail: 'n',
    num: 4,
    isZh: true,
    polyphonic: ['hàn'],
    inZhRange: 'true',
  },
  {
    origin: '语',
    pinyin: 'yǔ',
    initial: 'y',
    final: 'ǔ',
    first: 'y',
    finalHead: '',
    finalBody: 'ǔ',
    finalTail: '',
    num: 3,
    isZh: true,
    polyphonic: ['yǔ', 'yù'],
    inZhRange: 'true',
  },
  {
    origin: '拼',
    pinyin: 'pīn',
    initial: 'p',
    final: 'īn',
    first: 'p',
    finalHead: '',
    finalBody: 'ī',
    finalTail: 'n',
    num: 1,
    isZh: true,
    polyphonic: ['pīn'],
    inZhRange: 'true',
  },
  {
    origin: '音',
    pinyin: 'yīn',
    initial: 'y',
    final: 'īn',
    first: 'y',
    finalHead: '',
    finalBody: 'ī',
    finalTail: 'n',
    num: 1,
    isZh: true,
    polyphonic: ['yīn'],
    inZhRange: 'true',
  },
];
 */

多音字

设置 options.multiple 为 true 时,可以获取多音字的所有拼音。

只有 text 字段长度为 1(单个字符)时 options.multiple 才生效,否则不生效。

javascript
import { pinyin } from 'pinyin-pro';

// 获取多音
pinyin('好', { multiple: true }); // 'hǎo hào'
// 获取数组形式多音
pinyin('好', { multiple: true, type: 'array' }); // ["hǎo", "hào"]
// text 不为单个字符时 multiple 不生效
pinyin('好学', { multiple: true }); // hào xué

姓氏模式

设置 options.surname 为 head(只识别字符串开头的姓氏字符) 或者 all(识别字符串全部的姓氏字符) 可以开启姓氏模式,匹配到百家姓中的姓氏相关的字符将优先输出姓氏拼音。

javascript
import { pinyin } from 'pinyin-pro';

// 不开启姓氏模式
pinyin('我叫曾乐乐'); // 'wǒ jiào céng lè lè'

// 开启 head 姓氏模式
pinyin('我叫曾乐乐', { surname: 'head' }); // 'wǒ jiào zēng lè lè'

// 开启 all 姓氏模式(会将“乐”也识别为乐毅的yuè姓氏)
pinyin('我叫曾乐乐', { surname: 'all' }); // 'wǒ jiào zēng yuè yuè'

自定义分隔符

使用 options.separator 自定义拼音之间的分隔符,仅在 type: 'string' 时生效:

javascript
import { pinyin } from 'pinyin-pro';

pinyin('汉语拼音', { separator: '-' }); // 'hàn-yǔ-pīn-yīn'

非汉字字符处理

设置 options.nonZh ,可以处理非汉字字符的不同输出形式

javascript
import { pinyin } from 'pinyin-pro';

// 默认非汉字字符以空格间隔输出
pinyin('我very喜欢你'); // 'wǒ v e r y xǐ huān nǐ'

// 移除非汉字字符串,options.nonZh 设置为 removed
pinyin('我very喜欢你', { nonZh: 'removed' }); // 'wǒ xǐ huān nǐ'

// 非汉字字符串之间紧凑输出,options.nonZh 设置为 consecutive
pinyin('我very喜欢你', { nonZh: 'consecutive' }); // 'wǒ very xǐ huān nǐ'

拼音 ü 替换为 v

设置 options.v 为 true 之后,转换结果中的 ü 将会被替换为 v (带音调的 ǖ,ǘ,ǚ,ǜ 不会被转换):

javascript
import { pinyin } from 'pinyin-pro';

// 输出 ü
pinyin('吕布', { toneType: 'none' }); // lü bu
// 输出 v
pinyin('吕布', { toneType: 'none', v: true }); // lv bu
// 带音调的 ǖ,ǘ,ǚ,ǜ 不转换
pinyin('吕布', { v: true }); // lǚ bù
// 输出 v
pinyin('吕布', { type: 'num', v: true }); // lv3 bu4

选择不同的分词算法

设置 options.segmentit 以选择不同的分词算法,默认为最大概率算法:

javascript
import { pinyin } from 'pinyin-pro';

// 逆向最大匹配算法:速度最快
pinyin('小明硕士毕业于中国科学院计算所,后在日本京都大学深造', {
  segmentit: 1,
});

// 最大概率算法:识别最准确
pinyin('小明硕士毕业于中国科学院计算所,后在日本京都大学深造', {
  segmentit: 2,
});

// 最少分词数算法
pinyin('小明硕士毕业于中国科学院计算所,后在日本京都大学深造', {
  segmentit: 3,
});

声母排除 y 和 w

根据 wiki,y 和 w 不属于声母,但为了便于理解,在 pinyin-pro 中,默认将 y 和 w 作为声母。设置 options.initialPattern 为 standard 时,可将声母排除 y 和 w。

javascript
import { pinyin } from 'pinyin-pro';

pinyin('汉语拼音', {
  pattern: 'initial',
  initialPattern: 'standard',
  type: 'array'
}); // ['h', '', 'p', '']

语法及参数

语法

js
import { pinyin } from 'pinyin-pro';

interface BasicOptions {
    type: 'string' | 'array' | 'all';
    toneType?: 'symbol' | 'num' | 'none';
    pattern?: 'pinyin' | 'initial' | 'final' | 'num' | 'first' | 'finalHead' | 'finalBody' | 'finalTail';
    multiple?: boolean;
    removeNonZh?: boolean;
    nonZh?: 'spaced' | 'consecutive' | 'removed';
    v?: boolean;
    segmentit?: TokenizationAlgorithm; // v3.20.0+
    surname?: 'off' | 'head' | 'all'; // v3.21.0+
    mode?: 'normal' | 'surname'; // 已废弃,使用 surname 替代
    toneSandhi?: boolean | { yi?: boolean; bu?: boolean; thirdTone?: boolean };
    nonZhScope?: RegExp; // 3.24.0+
    initialPattern?: 'standard' | 'yw'; // 3.27.0+
    traditional?: boolean; // 3.28.0+
}

enum TokenizationAlgorithm {
  ReverseMaxMatch = 1,
  MaxProbability = 2,
  MinTokenization = 3,
}

interface AllData {
    origin: string;
    pinyin: string;
    initial: string;
    final: string;
    num: number;
    first: string;
    finalHead: string;
    finalBody: string;
    finalTail: string;
    isZh: boolean;
    polyphonic: string[]; // v3.20.0+
    inZhRange: boolean; // v3.20.0+
    result: string; // v3.24.0+
}

 // 返回转换后的信息
function pinyin(text: string, options?: BasicOptions): string | string[] | AllData[]

参数

  • text (必传):string 类型,需要进行拼音转换的字符串
  • options (可选):object 类型,转换输出的内容及格式,详细见下表

Packages Docs Zh Docs Use Polyphonic (`packages/docs/zh/docs/use/polyphonic.md`)

polyphonic

使用 polyphonic api 来获取多音字的全部读音。

::: tip
大多数情况下你只需要使用 pinyin api,它会自动识别文本中多音字的正确读音。polyphonic 是用来获取每个字的所有读音的而不是多音字在句子中的正确读音。
:::

示例

常规使用

使用 type 属性控制返回值的格式:

text
/* Detailed source-code truncated for AI context efficiency. */

不带音调

使用 toneType 属性控制音调的展示形式:

js
import { polyphonic } from 'pinyin-pro';

const resultNone = polyphonic('好好学习', { toneType: 'none' }); // ['hao', 'hao', 'xue', 'xi']

const resultNum = polyphonic('好好学习', { toneType: 'num' }); // ['hao3 hao4', 'hao3 hao4', 'xue2', 'xi2']

语法及参数

polyphonic 的参数大部分和 pinyin 是相同的。

语法

js
import { polyphonic } from 'pinyin-pro';

interface BasicOptions {
    type: 'string' | 'array' | 'all';
    toneType?: 'symbol' | 'num' | 'none';
    pattern?: 'pinyin' | 'initial' | 'final' | 'num' | 'first' | 'finalHead' | 'finalBody' | 'finalTail';
    nonZh?: 'spaced' | 'consecutive' | 'removed';
    v?: boolean;
}

interface AllData {
    origin: string;
    pinyin: string;
    initial: string;
    final: string;
    num: number;
    first: string;
    finalHead: string;
    finalBody: string;
    finalTail: string;
    isZh: boolean;
}

 // 返回转换后的信息
function polyphonic(text: string, options?: BasicOptions): string[] | string[][] | AllData[][]

参数

属性 类型 描述 可选值 说明 默认值
type string 返回的格式 string string 数组 string
array string 二维数组
all AllData 类型二维数组
toneType string 音调展示的形式 symbol 正常拼音音调 symbol
none 不展示
num 跟在拼音后以数字展示
pattern string 展示的内容 pinyin 拼音全拼 pinyin
initial 声母
final 韵母
num 音调对应数字
first 首字母
finalHead 韵头
finalBody 韵腹
finalTail 韵尾
nonZh string 非中文字符处理 spaced 空格间隔开 spaced
consecutive 连续
removed 从返回值中移除
v boolean 是否使用v替换返回值中的ü false 不替换 false
true 替换

Packages Docs Zh Docs Use Segment (`packages/docs/zh/docs/use/segment.md`)

segment

pinyin-pro 内部导出了 segment 函数,用于分词输出。

::: tip
为了保障分词的准确率,在使用 segment API 之前,需要先通过 addDict API 添加比较完备的词典如 @pinyin-pro/data/complete 或 @pinyin-pro/data/modern。
:::

示例

基础使用

js
import { segment, addDict } from 'pinyin-pro';
import CompleteDict from '@pinyin-pro/data/complete';

addDict(CompleteDict);

const result = segment('小明硕士毕业于中国科学院计算所,后在日本京都大学深造');

// 转换结果:
[
  { origin: '小', result: 'xiǎo' },
  { origin: '明', result: 'míng' },
  { origin: '硕士', result: 'shuòshì' },
  { origin: '毕业', result: 'bìyè' },
  { origin: '于', result: 'yú' },
  { origin: '中国科学院', result: 'zhōngguókēxuéyuàn' },
  { origin: '计算所', result: 'jìsuànsuǒ' },
  { origin: ',', result: ',' },
  { origin: '后', result: 'hòu' },
  { origin: '在', result: 'zài' },
  { origin: '日本京都大学', result: 'rìběnjīngdūdàxué' },
  { origin: '深造', result: 'shēnzào' },
];

不同输出格式

通过 format 参数指定不同的输出格式。

AllSegment

js
import { segment, OutputFormat, addDict } from 'pinyin-pro';
import CompleteDict from '@pinyin-pro/data/complete';

addDict(CompleteDict);

const result = segment('小明硕士毕业于中国科学院计算所,后在日本京都大学深造', {
  format: OutputFormat.AllSegment,
});

// 转换结果:
[
  { origin: '小', result: 'xiǎo' },
  { origin: '明', result: 'míng' },
  { origin: '硕士', result: 'shuòshì' },
  { origin: '毕业', result: 'bìyè' },
  { origin: '于', result: 'yú' },
  { origin: '中国科学院', result: 'zhōngguókēxuéyuàn' },
  { origin: '计算所', result: 'jìsuànsuǒ' },
  { origin: ',', result: ',' },
  { origin: '后', result: 'hòu' },
  { origin: '在', result: 'zài' },
  { origin: '日本京都大学', result: 'rìběnjīngdūdàxué' },
  { origin: '深造', result: 'shēnzào' },
];

AllArray

js
import { segment, OutputFormat, addDict } from 'pinyin-pro';
import CompleteDict from '@pinyin-pro/data/complete';

addDict(CompleteDict);

const result = segment('小明硕士毕业于中国科学院计算所,后在日本京都大学深造', {
  format: OutputFormat.AllArray,
});

// 转换结果:
[
  [{ origin: '小', result: 'xiǎo' }],
  [{ origin: '明', result: 'míng' }],
  [
    { origin: '硕', result: 'shuò' },
    { origin: '士', result: 'shì' },
  ],
  [
    { origin: '毕', result: 'bì' },
    { origin: '业', result: 'yè' },
  ],
  [{ origin: '于', result: 'yú' }],
  [
    { origin: '中', result: 'zhōng' },
    { origin: '国', result: 'guó' },
    { origin: '科', result: 'kē' },
    { origin: '学', result: 'xué' },
    { origin: '院', result: 'yuàn' },
  ],
  [
    { origin: '计', result: 'jì' },
    { origin: '算', result: 'suàn' },
    { origin: '所', result: 'suǒ' },
  ],
  [{ origin: ',', result: ',' }],
  [{ origin: '后', result: 'hòu' }],
  [{ origin: '在', result: 'zài' }],
  [
    { origin: '日', result: 'rì' },
    { origin: '本', result: 'běn' },
    { origin: '京', result: 'jīng' },
    { origin: '都', result: 'dū' },
    { origin: '大', result: 'dà' },
    { origin: '学', result: 'xué' },
  ],
  [
    { origin: '深', result: 'shēn' },
    { origin: '造', result: 'zào' },
  ],
];

AllString

js
import { segment, OutputFormat, addDict } from 'pinyin-pro';
import CompleteDict from '@pinyin-pro/data/complete';

addDict(CompleteDict);

const result = segment('小明硕士毕业于中国科学院计算所,后在日本京都大学深造', {
  format: OutputFormat.AllString,
});

// 转换结果:
{
  origin: "小 明 硕士 毕业 于 中国科学院 计算所 , 后 在 日本京都大学 深造",
  result: "xiǎo míng shuòshì bìyè yú zhōngguókēxuéyuàn jìsuànsuǒ , hòu zài rìběnjīngdūdàxué shēnzào",
}

PinyinSegment

js
import { segment, OutputFormat, addDict } from 'pinyin-pro';
import CompleteDict from '@pinyin-pro/data/complete';

addDict(CompleteDict);

const result = segment('小明硕士毕业于中国科学院计算所,后在日本京都大学深造', {
  format: OutputFormat.PinyinSegment,
});

// 转换结果:
[
  'xiǎo',
  'míng',
  'shuòshì',
  'bìyè',
  'yú',
  'zhōngguókēxuéyuàn',
  'jìsuànsuǒ',
  ',',
  'hòu',
  'zài',
  'rìběnjīngdūdàxué',
  'shēnzào',
];

PinyinArray

js
import { segment, OutputFormat, addDict } from 'pinyin-pro';
import CompleteDict from '@pinyin-pro/data/complete';

addDict(CompleteDict);

const result = segment('小明硕士毕业于中国科学院计算所,后在日本京都大学深造', {
  format: OutputFormat.PinyinArray,
});

// 转换结果:
[
  ['xiǎo'],
  ['míng'],
  ['shuò', 'shì'],
  ['bì', 'yè'],
  ['yú'],
  ['zhōng', 'guó', 'kē', 'xué', 'yuàn'],
  ['jì', 'suàn', 'suǒ'],
  [','],
  ['hòu'],
  ['zài'],
  ['rì', 'běn', 'jīng', 'dū', 'dà', 'xué'],
  ['shēn', 'zào'],
];

PinyinString

js
import { segment, OutputFormat, addDict } from 'pinyin-pro';
import CompleteDict from '@pinyin-pro/data/complete';

addDict(CompleteDict);

const result = segment('小明硕士毕业于中国科学院计算所,后在日本京都大学深造', {
  format: OutputFormat.PinyinString,
});

// 转换结果:
('xiǎo míng shuòshì bìyè yú zhōngguókēxuéyuàn jìsuànsuǒ , hòu zài rìběnjīngdūdàxué shēnzào');

ZhSegment

js
import { segment, OutputFormat, addDict } from 'pinyin-pro';
import CompleteDict from '@pinyin-pro/data/complete';

addDict(CompleteDict);

const result = segment('小明硕士毕业于中国科学院计算所,后在日本京都大学深造', {
  format: OutputFormat.ZhSegment,
});

// 转换结果:
[
  '小',
  '明',
  '硕士',
  '毕业',
  '于',
  '中国科学院',
  '计算所',
  ',',
  '后',
  '在',
  '日本京都大学',
  '深造',
];

ZhArray

js
import { segment, OutputFormat, addDict } from 'pinyin-pro';
import CompleteDict from '@pinyin-pro/data/complete';

addDict(CompleteDict);

const result = segment('小明硕士毕业于中国科学院计算所,后在日本京都大学深造', {
  format: OutputFormat.ZhArray,
});

// 转换结果:
[
  ['小'],
  ['明'],
  ['硕', '士'],
  ['毕', '业'],
  ['于'],
  ['中', '国', '科', '学', '院'],
  ['计', '算', '所'],
  [','],
  ['后'],
  ['在'],
  ['日', '本', '京', '都', '大', '学'],
  ['深', '造'],
];

ZhString

js
import { segment, OutputFormat, addDict } from 'pinyin-pro';
import CompleteDict from '@pinyin-pro/data/complete';

addDict(CompleteDict);

const result = segment('小明硕士毕业于中国科学院计算所,后在日本京都大学深造', {
  format: OutputFormat.ZhString,
});

// 转换结果:
('小 明 硕士 毕业 于 中国科学院 计算所 , 后 在 日本京都大学 深造');

自定义分隔符

通过 separator 参数自定义分隔符。仅对于 AllString、PinyinString、ZhString 三种输出格式生效。

js
import { segment, OutputFormat, addDict } from 'pinyin-pro';
import CompleteDict from '@pinyin-pro/data/complete';

addDict(CompleteDict);

const result = segment('小明硕士毕业于中国科学院计算所,后在日本京都大学深造', {
  format: OutputFormat.AllString,
  separator: '/',
});

// 转换结果:
{
  origin: "小/明/硕士/毕业/于/中国科学院/计算所/,/后/在/日本京都大学/深造",
  result:
    "xiǎo/míng/shuòshì/bìyè/yú/zhōngguókēxuéyuàn/jìsuànsuǒ/,/hòu/zài/rìběnjīngdūdàxué/shēnzào",
}

语法及参数

除 format 和 separator 参数外,其他参数的作用和 pinyin API 相同。

ts
import { segment, OutputFormat } from 'pinyin-pro';

interface SegmentOptions {
  toneType?: 'symbol' | 'num' | 'none';
  removeNonZh?: boolean;
  nonZh?: 'spaced' | 'consecutive' | 'removed';
  v?: boolean;
  segmentit?: TokenizationAlgorithm;
  surname?: 'off' | 'head' | 'all';
  mode?: 'normal' | 'surname';
  toneSandhi?: boolean | { yi?: boolean; bu?: boolean; thirdTone?: boolean };
  nonZhScope?: RegExp;
  separator?: string;
  format?: OutputFormat;
  initialPattern?: 'standard' | 'yw'; // 3.27.0+
  traditional?: boolean; // 3.28.0+
}

function segment(text: string, options?: SegmentOptions);

Packages Docs Zh Docs Use Traditional (`packages/docs/zh/docs/use/traditional.md`)

addTraditionalDict

pinyin-pro 内部导出了 addTraditionalDict 函数,用于更好的识别繁体字。

::: tip
需要安装 @pinyin-pro/data 来引入繁体字映射表

bash
npm install @pinyin-pro/data

:::

示例

pinyin

js
import { pinyin, addTraditionalDict } from 'pinyin-pro';
import TraditionalDict from '@pinyin-pro/data/traditional';

// 使用 addTraditionalDict 前
const result1 = pinyin('一个轉盤'); // 结果: yī gè zhuǎn pán

// 使用 addTraditionalDict 后
addTraditionalDict(TraditionalDict);
const result2 = pinyin('一个轉盤', { traditional: true }); // 结果: yī gè zhuàn pán

html

text
/* Detailed source-code truncated for AI context efficiency. */

segment

js
import { segment, addTraditionalDict } from 'pinyin-pro';
import TraditionalDict from '@pinyin-pro/data/traditional';

// 使用 addTraditionalDict 前
const result1 = segment('一个轉盤');
/*
[
  { "origin": "一", "result": "yí" },
  { "origin": "个", "result": "gè" },
  { "origin": "轉", "result": "zhuǎn" },
  { "origin": "盤", "result": "pán" }
]
*/

// 使用 addTraditionalDict 后
addTraditionalDict(TraditionalDict);
const result2 = segment('一个轉盤', { traditional: true });
/*
[
  { "origin": "一", "result": "yí" },
  { "origin": "个", "result": "gè" },
  { "origin": "轉", "result": "zhuàn" },
  { "origin": "盤", "result": "pán" }
]
*/

语法及参数

接收一个繁简字映射表对象作为参数。

ts
import { addTraditionalDict } from 'pinyin-pro';

function addTraditionalDict(dict: Record<string, string>);

// dict 示例
const Dict = {
  "萬": "万",
  "與": "与",
  "醜": "丑",
  "專": "专",
  "業": "业",
  "東": "东",
  "絲": "丝",
  "丟": "丢",
  "兩": "两",
}

--- METRICS ---