# Technical Documentation: zh-lx/pinyin-pro

> ℹ️ **Provenance:** Multi-Tier Ingestion · [CodeWiki Reference](https://codewiki.google/github.com/zh-lx/pinyin-pro)

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

# pinyin-pro-data

## 📖 介绍

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

- [@pinyin-pro/data/modern.json](https://github.com/zh-lx/pinyin-pro/blob/main/packages/data/json/modern.json): 《现代汉语词典(第 7 版)》词语拼音合集(gzip 压缩后大概 0.6 MB)
- [@pinyin-pro/data/complete.json](https://github.com/zh-lx/pinyin-pro/blob/main/packages/data/json/complete.json): jieba 中文分词库词语拼音合集(gzip 压缩后大概 3.99 MB)
- [@pinyin-pro/data/chars.json](https://github.com/zh-lx/pinyin-pro/blob/main/packages/data/json/chars.json): 部分补充生僻字字典(gzip 压缩后大概 0.1KB)
- [@pinyin-pro/data/buddhist.json](https://github.com/zh-lx/pinyin-pro/blob/main/packages/data/json/buddhist.json): 佛经（佛教典籍）专用拼音词典（128 条，opt-in）

## 🔨 安装

选择合适的包管理器

```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](https://pinyin-pro.cn)

---

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

<a href="https://github.com/zh-lx/pinyin-pro"><img src="https://cdn.jsdelivr.net/gh/zh-lx/static-img/pinyin-pro/logo.svg" alt="logo" width="500" /></a>

[](https://www.npmjs.com/package/pinyin-pro)
[](https://github.com/zh-lx/pinyin-pro)
[](https://github.com/zh-lx/pinyin-pro/actions)
[](https://npmcharts.netlify.app/compare/pinyin-pro?minimal=true)
[](https://app.codecov.io/gh/zh-lx/pinyin-pro)
[](https://deepscan.io/dashboard#view=project&tid=20303&pid=26161&bid=829070)
[](https://opensource.org/licenses/MIT)
[](https://bundlephobia.com/package/pinyin-pro)
[](https://github.com/zh-lx/pinyin-pro)

### 📖 介绍

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

[中文文档](https://pinyin-pro.cn) | [English Docs](https://pinyin-pro.cn/en) | [在线运行](https://pinyin-pro.cn/run/run)

### 🎨 特色功能

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

### 🔨 安装

npm 安装

```html
npm install pinyin-pro
```

浏览器引入

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

### 💡 使用示例

全部功能的使用说明文档请查看[在线文档](https://pinyin-pro.cn/use/pinyin.html)

- 获取拼音，更多功能请查看[pinyin API](https://pinyin-pro.cn/use/pinyin.html)

  ```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](https://pinyin-pro.cn/use/match.html)

  <details>
    <summary>点击展开文本和拼音匹配示例</summary>

  ```js
  import { match } from "pinyin-pro";

  // 支持首字母匹配
  match("中文拼音", "zwp"); // [0, 1, 2]

  // 支持全拼匹配
  match("中文拼音", "zhongwenpin"); // [0, 1, 2]

  // 支持混合匹配
  match("中文拼音", "zhongwp"); // [0, 1, 2]
  ```

  </details>

- 拼音格式转换，更多功能请查看[convert API](https://pinyin-pro.cn/use/convert.html)

  <details>
    <summary>点击展开拼音格式转换示例</summary>

  ```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'
  ```

  </details>

- 分词并获取拼音，更多配置请查看[segment API](https://pinyin-pro.cn/use/segment.html)

  <details>
    <summary>点击展开 segment 基础使用示例</summary>

  ```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ǔ"
  ```

  </details>

- 获取带汉字拼音的 HTML 字符串，更多配置请查看[html API](https://pinyin-pro.cn/use/html.html)

  <details>
    <summary>点击展开 HTML 字符串示例</summary>

  ```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>
  */
  ```

  上述结果浏览器中预览效果如下：
  <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>

  </details>

- 更多的 API 请查看[pinyin-pro 官网](https://pinyin-pro.cn/)

### 🏆 竞品对比

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

- 准确率测试数据: [accuracy](https://github.com/zh-lx/pinyin-pro/blob/main/packages/pinyin-pro/scripts/benchmark/accuracy.ts)
- 性能测试数据：[speed](https://github.com/zh-lx/pinyin-pro/blob/main/packages/pinyin-pro/scripts/benchmark/speed.ts)
<table>
    <tr>
        <th colspan="2">对比项</th>
        <th>pinyin</th>
        <th>@napi-rs/pinyin</th>
        <th>pinyin-pro</th>
    </tr>
    <tr>
        <td rowspan="2" colspan="2">准确率</td>
        <td>😕 Node 版: 94.097%</td>
        <td rowspan="2">😕 94.097%</td>
        <td rowspan="2">🤩 99.846%</td>
    </tr>
    <tr>
        <td>😕 Web 版: 91.170%	</td>
    </tr>
    <tr>
        <td rowspan="5">性能</td>
        <td>首次使用字典初始化时长</td>
        <td>🚀 14.261ms</td>
        <td>🐢 160.769ms</td>
        <td>🚀 8.412ms</td>
    </tr>
    <tr>
        <td>10k字转换耗时</td>
        <td>🚲 74.442ms</td>
        <td>🚀 4.298ms</td>
        <td>🚀 7.216ms</td>
    </tr>
    <tr>
        <td>100k字转换耗时</td>
        <td>🐢 6287.332ms</td>
        <td>🚀 29.32ms</td>
        <td>🚀 45.471ms</td>
    </tr>
    <tr>
        <td>1m字转换耗时</td>
        <td>⛔ 内存溢出转换失败</td>
        <td>🚀 297.41ms</td>
        <td>🚀 328.338ms</td>
    </tr>
    <tr>
        <td>10m字转换耗时</td>
        <td>⛔ 内存溢出转换失败</td>
        <td>🚀 3907.278ms</td>
        <td>🚀 3375.192ms</td>
    </tr>
    <tr>
        <td rowspan="2">兼容性</td>
        <td>Web 环境</td>
        <td>✔️ 支持</td>
        <td>❌ 不支持</td>
        <td>✔️ 支持</td>
    </tr>
    <tr>
        <td>Node 环境</td>
        <td>✔️ 支持</td>
        <td>✔️ 支持</td>
        <td>✔️ 支持</td>
    </tr>
</table>

### 📦 API Size

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

<table>
    <thead>
        <tr>
            <th>API</th>
            <th>ESM</th>
            <th>UMD</th>
        </tr>
    </thead>
    <tbody>
    <tr><td>pinyin</td><td>307.03 KB (gzip 134.83 KB)</td><td rowspan="7">317.47 KB (gzip 138.33 KB)</td></tr>
    <tr><td>segment</td><td>305.79 KB (gzip 134.04 KB)</td></tr>
    <tr><td>match</td><td>185.67 KB (gzip 80.90 KB)</td></tr>
    <tr><td>convert</td><td>1.78 KB (gzip 0.98 KB)</td></tr>
    <tr><td>html</td><td>307.87 KB (gzip 135.13 KB)</td></tr>
    <tr><td>polyphonic</td><td>180.75 KB (gzip 78.83 KB)</td></tr>
    <tr><td>总体积</td><td>561.18 KB (gzip 158.13 KB)</td></tr>
    </tbody>
</table>

### 📠 反馈

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

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

<div style="display: flex;">
  <img src="https://user-images.githubusercontent.com/73059627/226233976-5dbb9daa-6620-4d16-a2b0-359055dcafe1.png" width="200" >
  <img src="https://user-images.githubusercontent.com/73059627/226233691-848b2a40-f1a9-414e-a80f-3fc6c6209eb1.png" width="200" >
</div>

### 🧰 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 安装

```
npm install pinyin-pro
```

yarn 安装

```
yarn add pinyin-pro
```

## 使用

浏览器端：

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

node 端：

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

## 参数

`pinyin(word, options)` 接收两个参数<br>

- <b>word：</b>必填。String 类型，需要转化为拼音的中文
- <b>options：</b>可选。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 安装

```
npm install pinyin-pro
```

yarn 安装

```
yarn add pinyin-pro
```

## 使用

浏览器端：

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

node 端：

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

## 参数

`pinyin(word, options)` 接收两个参数<br>

- <b>word：</b>必填。String 类型，需要转化为拼音的中文
- <b>options：</b>可选。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`)

[](https://github.com/zh-lx/pinyin-pro)

[](https://www.npmjs.com/package/pinyin-pro)
[](https://github.com/zh-lx/pinyin-pro)
[](https://travis-ci.com/github/zh-lx/pinyin-pro)
[](https://npmcharts.com/compare/pinyin-pro?minimal=true)
[](https://coveralls.io/github/zh-lx/pinyin-pro?branch=main)
[](https://opensource.org/licenses/MIT)
[](https://github.com/zh-lx/pinyin-pro)

## 特色功能

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

## 版本更新

当前版本： 3.3.0 -> 3.3.1

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

点击查看 [版本更新文档](./CHANGELOG.md)

## 安装

npm 安装

```
npm install pinyin-pro
```

yarn 安装

```
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)` 接收两个参数<br>

- <b>word：</b>必填。String 类型，需要转化为拼音的中文
- <b>options：</b>可选。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`)

[](https://github.com/zh-lx/pinyin-pro)

[](https://www.npmjs.com/package/pinyin-pro)
[](https://github.com/zh-lx/pinyin-pro)
[](https://travis-ci.com/github/zh-lx/pinyin-pro)
[](https://npmcharts.com/compare/pinyin-pro?minimal=true)
[](https://coveralls.io/github/zh-lx/pinyin-pro?branch=main)
[](https://opensource.org/licenses/MIT)
[](https://github.com/zh-lx/pinyin-pro)

## 特色功能

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

## 版本更新

当前版本： 3.3.1 -> 3.4.0

- 新增功能
  - 支持姓氏模式拼音识别，具体用法见[姓氏模式](#surname)
  - 支持自定义拼音功能，具体用法见[自定义拼音](#custom)
- 问题修复
  修复文本过长时堆栈溢出问题
- 字音校准
  - 褚: 'zhǔ' -> 'chǔ zhǔ'
  - 俞: 'yù' -> 'yú yù'
  - 臧: 'zàng' -> 'zāng'
  - 贲: 'bì' -> 'bēn bì'
  - 莘: 'xīn' -> 'shēn xīn'
  - 郦: 'zhí' -> 'lì zhí'

点击查看 [版本更新文档](./CHANGELOG.md)

## 安装

npm 安装

```
npm install pinyin-pro
```

yarn 安装

```
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)` 接收两个参数<br>

- <b>word：</b>必填。String 类型，需要转化为拼音的中文
- <b>options：</b>可选。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"]
```

### <a id="surname">姓氏模式</a>

通过设置 `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'
```

### <a id="custom">自定义拼音</a>

包内部导出了 `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 贡献](./docs/contribute.md)

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

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

---

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

[](https://github.com/zh-lx/pinyin-pro)

[](https://www.npmjs.com/package/pinyin-pro)
[](https://github.com/zh-lx/pinyin-pro)
[](https://travis-ci.com/github/zh-lx/pinyin-pro)
[](https://npmcharts.com/compare/pinyin-pro?minimal=true)
[](https://coveralls.io/github/zh-lx/pinyin-pro?branch=main)
[](https://opensource.org/licenses/MIT)
[](https://github.com/zh-lx/pinyin-pro)

## 特色功能

- [获取汉字、词语、句子等多种格式的拼音](#pinyin)
- [获取声母](#initial)
- [获取韵母](#final)
- [获取拼音首字母](#first)
- [获取音调](#num)
- [获取多音字的多种拼音](#multiple)
- [支持人名姓氏模式](#surname)
- [支持自定义拼音](#custom)
- [支持字符串和数组两种输出形式](#pinyin)
- [支持拼音文本匹配功能](#match)

## 版本更新

当前版本： 3.4.1 -> 3.5.0

- 新增功能
  - 新增 `match` api 以支持[拼音文本匹配功能](#match)

点击查看 [版本更新文档](./CHANGELOG.md)

## 安装

npm 安装

```
npm install pinyin-pro
```

yarn 安装

```
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)` 接收两个参数<br>

- <b>word：</b>必填。String 类型，需要转化为拼音的中文
- <b>options：</b>可选。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 |

## 使用示例

### <a id="pinyin">获取拼音</a>

```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"]
```

### <a id="initial">获取声母</a>

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

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

### <a id="final">获取韵母</a>

```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']
```

### <a id="num">获取音调</a>

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

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

### <a id="first">获取拼音首字母</a>

```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']
```

### <a id="multiple">获取单个字的多音</a>

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

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

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

### <a id="surname">姓氏模式</a>

通过设置 `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'
```

### <a id="custom">自定义拼音</a>

包内部导出了 `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'
```

### <a id="match">拼音匹配</a>

包内含 `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 贡献](./docs/contribute.md)

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

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

---

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

[](https://github.com/zh-lx/pinyin-pro)

[](https://www.npmjs.com/package/pinyin-pro)
[](https://github.com/zh-lx/pinyin-pro)
[](https://travis-ci.com/github/zh-lx/pinyin-pro)
[](https://npmcharts.com/compare/pinyin-pro?minimal=true)
[](https://coveralls.io/github/zh-lx/pinyin-pro?branch=main)
[](https://opensource.org/licenses/MIT)
[](https://github.com/zh-lx/pinyin-pro)

## 特色功能

- [获取汉字、词语、句子等多种格式的拼音](#pinyin)
- [获取声母](#initial)
- [获取韵母](#final)
- [获取拼音首字母](#first)
- [获取音调](#num)
- [获取多音字的多种拼音](#multiple)
- [支持人名姓氏模式](#surname)
- [支持自定义拼音](#custom)
- [支持字符串和数组两种输出形式](#pinyin)
- [支持拼音文本匹配功能](#match)

## 版本更新

当前版本： 3.5.0 -> 3.6.0

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

点击查看 [版本更新文档](./CHANGELOG.md)

## 安装

npm 安装

```
npm install pinyin-pro
```

yarn 安装

```
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)` 接收两个参数<br>

- <b>word：</b>必填。String 类型，需要转化为拼音的中文
- <b>options：</b>可选。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  |

## 使用示例

### <a id="pinyin">获取拼音</a>

```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"]
```

### <a id="initial">获取声母</a>

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

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

### <a id="final">获取韵母</a>

```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']
```

### <a id="num">获取音调</a>

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

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

### <a id="first">获取拼音首字母</a>

```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']
```

### <a id="multiple">获取单个字的多音</a>

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

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

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

### <a id="surname">姓氏模式</a>

通过设置 `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'
```

### <a id="removeNonZh">过滤非汉字字符</a>

通过设置 `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'
```

### <a id="custom">自定义拼音</a>

包内部导出了 `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'
```

### <a id="match">拼音匹配</a>

包内含 `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 贡献](./docs/contribute.md)

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

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

---

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

[](https://github.com/zh-lx/pinyin-pro)

[](https://www.npmjs.com/package/pinyin-pro)
[](https://github.com/zh-lx/pinyin-pro)
[](https://travis-ci.com/github/zh-lx/pinyin-pro)
[](https://npmcharts.com/compare/pinyin-pro?minimal=true)
[](https://coveralls.io/github/zh-lx/pinyin-pro?branch=main)
[](https://opensource.org/licenses/MIT)
[](https://github.com/zh-lx/pinyin-pro)

## 特色功能

- [获取汉字、词语、句子等多种格式的拼音](#pinyin)
- [获取声母](#initial)
- [获取韵母](#final)
- [获取拼音首字母](#first)
- [获取音调](#num)
- [获取多音字的多种拼音](#multiple)
- [支持人名姓氏模式](#surname)
- [支持自定义拼音](#custom)
- [支持字符串和数组两种输出形式](#pinyin)
- [支持拼音文本匹配功能](#match)

## 版本更新

当前版本： 3.7.0 -> 3.7.1

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

点击查看 [版本更新文档](./CHANGELOG.md)

## 安装

npm 安装

```
npm install pinyin-pro
```

yarn 安装

```
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)` 接收两个参数<br>

- <b>word：</b>必填。String 类型，需要转化为拼音的中文
- <b>options：</b>可选。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  |

## 使用示例

### <a id="pinyin">获取拼音</a>

```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"]
```

### <a id="initial">获取声母</a>

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

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

### <a id="final">获取韵母</a>

```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']
```

### <a id="num">获取音调</a>

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

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

### <a id="first">获取拼音首字母</a>

```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']
```

### <a id="multiple">获取单个字的多音</a>

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

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

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

### <a id="surname">姓氏模式</a>

通过设置 `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'
```

### <a id="removeNonZh">过滤非汉字字符</a>

通过设置 `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'
```

### <a id="custom">自定义拼音</a>

包内部导出了 `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'
```

### <a id="match">拼音匹配</a>

包内含 `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 贡献](./docs/contribute.md)

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

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

---

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

[](https://github.com/zh-lx/pinyin-pro)

[](https://www.npmjs.com/package/pinyin-pro)
[](https://github.com/zh-lx/pinyin-pro)
[](https://travis-ci.com/github/zh-lx/pinyin-pro)
[](https://npmcharts.com/compare/pinyin-pro?minimal=true)
[](https://coveralls.io/github/zh-lx/pinyin-pro?branch=main)
[](https://opensource.org/licenses/MIT)
[](https://github.com/zh-lx/pinyin-pro)

## 特色功能

- [获取汉字、词语、句子等多种格式的拼音](#pinyin)
- [获取声母](#initial)
- [获取韵母](#final)
- [获取拼音首字母](#first)
- [获取音调](#num)
- [获取多音字的多种拼音](#multiple)
- [支持人名姓氏模式](#surname)
- [支持自定义拼音](#custom)
- [支持字符串和数组两种输出形式](#pinyin)
- [支持拼音文本匹配功能](#match)

## 版本更新

当前版本： 3.7.2 -> 3.8.0

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

点击查看 [版本更新文档](./CHANGELOG.md)

## 安装

npm 安装

```
npm install pinyin-pro
```

yarn 安装

```
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)` 接收两个参数<br>

- <b>word：</b>必填。String 类型，需要转化为拼音的中文
- <b>options：</b>可选。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 |

## 使用示例

### <a id="pinyin">获取拼音</a>

```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"]
```

### <a id="initial">获取声母</a>

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

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

### <a id="final">获取韵母</a>

```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']
```

### <a id="num">获取音调</a>

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

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

### <a id="first">获取拼音首字母</a>

```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']
```

### <a id="multiple">获取单个字的多音</a>

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

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

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

### <a id="surname">姓氏模式</a>

通过设置 `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'
```

### <a id="removeNonZh">过滤非汉字字符</a>

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

```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'
```

### <a id="nonZh">定义非汉字字符输出形式</a>

通过设置 `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ǐ' 移除非汉字字符
```

### <a id="custom">自定义拼音</a>

包内部导出了 `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'
```

### <a id="match">拼音匹配</a>

包内含 `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 贡献](./docs/contribute.md)

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

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

---

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

[](https://github.com/zh-lx/pinyin-pro)

[](https://www.npmjs.com/package/pinyin-pro)
[](https://github.com/zh-lx/pinyin-pro)
[](https://travis-ci.com/github/zh-lx/pinyin-pro)
[](https://npmcharts.com/compare/pinyin-pro?minimal=true)
[](https://coveralls.io/github/zh-lx/pinyin-pro?branch=main)
[](https://opensource.org/licenses/MIT)
[](https://github.com/zh-lx/pinyin-pro)

## 特色功能

- [获取汉字、词语、句子等多种格式的拼音](#pinyin)
- [获取声母](#initial)
- [获取韵母](#final)
- [获取拼音首字母](#first)
- [获取音调](#num)
- [获取多音字的多种拼音](#multiple)
- [支持人名姓氏模式](#surname)
- [支持自定义拼音](#custom)
- [支持字符串和数组两种输出形式](#pinyin)
- [支持拼音文本匹配功能](#match)

## 版本更新

当前版本： 3.8.3 -> 3.9.0

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

点击查看 [版本更新文档](./CHANGELOG.md)

## 安装

npm 安装

```
npm install pinyin-pro
```

yarn 安装

```
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)` 接收两个参数<br>

- <b>word：</b>必填。String 类型，需要转化为拼音的中文
- <b>options：</b>可选。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  |

## 使用示例

### <a id="pinyin">获取拼音</a>

```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"]
```

### <a id="initial">获取声母</a>

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

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

### <a id="final">获取韵母</a>

```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']
```

### <a id="num">获取音调</a>

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

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

### <a id="first">获取拼音首字母</a>

```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']
```

### <a id="multiple">获取单个字的多音</a>

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

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

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

### <a id="surname">姓氏模式</a>

通过设置 `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'
```

### <a id="removeNonZh">过滤非汉字字符</a>

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

```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'
```

### <a id="nonZh">定义非汉字字符输出形式</a>

通过设置 `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ǐ' 移除非汉字字符
```

### <a id="custom">自定义拼音</a>

包内部导出了 `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'
```

### <a id="match">拼音匹配</a>

包内含 `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 贡献](./docs/contribute.md)

使用遇到问题或者需要功能支持欢迎提 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.

<table>
    <thead>
        <tr>
            <th>API</th>
            <th>ESM</th>
            <th>UMD</th>
        </tr>
    </thead>
    <tbody>
    <tr><td>pinyin</td><td>307.03 KB (gzip 134.83 KB)</td><td rowspan="7">317.47 KB (gzip 138.33 KB)</td></tr>
    <tr><td>segment</td><td>305.79 KB (gzip 134.04 KB)</td></tr>
    <tr><td>match</td><td>185.67 KB (gzip 80.90 KB)</td></tr>
    <tr><td>convert</td><td>1.78 KB (gzip 0.98 KB)</td></tr>
    <tr><td>html</td><td>307.87 KB (gzip 135.13 KB)</td></tr>
    <tr><td>polyphonic</td><td>180.75 KB (gzip 78.83 KB)</td></tr>
    <tr><td>Total</td><td>561.18 KB (gzip 158.13 KB)</td></tr>
    </tbody>
</table>

---

### 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](https://github.com/zh-lx/pinyin-pro/pull/356)
- 【perf】`match`: Reconstruct matching paths with backpointers to reduce array allocations [#367](https://github.com/zh-lx/pinyin-pro/pull/367)
- 【perf】`match`: Optimize prefix matching to avoid unnecessary string processing [#369](https://github.com/zh-lx/pinyin-pro/pull/369)
- 【perf】`polyphonic`: Reuse parsed `final` parts to avoid repeated work in `type: 'all'` mode [#372](https://github.com/zh-lx/pinyin-pro/pull/372)
- 【perf】`match`: Reuse split text characters to avoid repeated splitting [#373](https://github.com/zh-lx/pinyin-pro/pull/373)
- 【perf】Optimize node lookups and queue handling while building the AC automaton [#374](https://github.com/zh-lx/pinyin-pro/pull/374)
- 【perf】Batch consecutive custom-pinyin updates to reduce repeated custom dictionary rebuilds [#375](https://github.com/zh-lx/pinyin-pro/pull/375)

## 3.29.4

- 【fix】Tolerate runtimes that forbid timers during module initialization, such as Cloudflare Workers [#364](https://github.com/zh-lx/pinyin-pro/pull/364)
- 【perf】`match`: Reuse per-character pinyin forms in DP to avoid repeated computation [#362](https://github.com/zh-lx/pinyin-pro/pull/362)、[#360](https://github.com/zh-lx/pinyin-pro/pull/360)
- 【perf】`segmentit`: Stop prebuilding the AC automaton via `setTimeout` in Node to further reduce `import` cost [#361](https://github.com/zh-lx/pinyin-pro/pull/361)

## 3.29.3

Thank you [@luojiyin1987](https://github.com/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](https://github.com/zh-lx/pinyin-pro/pull/344)
- 【perf】`segmentit`: Reuse child lookup during AC matching [#346](https://github.com/zh-lx/pinyin-pro/pull/346)
- 【perf】`segmentit`: Reconstruct the max-probability path with backpointers [#348](https://github.com/zh-lx/pinyin-pro/pull/348)
- 【perf】`splitString`: Use a native `split` fast path for BMP-only text [#349](https://github.com/zh-lx/pinyin-pro/pull/349)
- 【perf】`pinyin`: Skip the reduplication processor when the text has no `々` [#351](https://github.com/zh-lx/pinyin-pro/pull/351)

## 3.29.2

Thank you [@luojiyin1987](https://github.com/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](https://github.com/zh-lx/pinyin-pro/pull/342)
- 【fix】`customPinyin`: Prevent `pattern` accumulation on repeated updates [#340](https://github.com/zh-lx/pinyin-pro/pull/340)
- 【perf】`pinyin`: Reuse split characters across multiple `middleware` [#338](https://github.com/zh-lx/pinyin-pro/pull/338)
- 【perf】`pinyin`: Avoid splitting non-polyphonic pinyin with `split` [#336](https://github.com/zh-lx/pinyin-pro/pull/336)

## 3.29.1

- 【perf】Postpone the construction of the AC automaton to reduce main thread blocking when `import pinyin-pro` [#333](https://github.com/zh-lx/pinyin-pro/pull/333)
- 【perf】Optimize repeated calculations in `middlewareMultiple` [#330](https://github.com/zh-lx/pinyin-pro/pull/330)
- 【fix】Fix the issue where non-Chinese characters are not completely removed by `nonZhScope` [#329](https://github.com/zh-lx/pinyin-pro/pull/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](https://github.com/zh-lx/pinyin-pro/pull/323)
- 【perf】Optimized ESM packaging configuration to ensure only necessary code is imported during tree shaking, reducing the size of each API [#327](https://github.com/zh-lx/pinyin-pro/pull/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](https://github.com/zh-lx/pinyin-pro/pull/306)

## 3.28.0

- 【feat】Added `addTraditionalDict` API to better recognize traditional Chinese characters [#303](https://github.com/zh-lx/pinyin-pro/pull/303)

## 3.27.0

- 【feat】Added `initialPattern` option to the `pinyin` API to exclude `y` and `w` from the initial consonants [#295](https://github.com/zh-lx/pinyin-pro/pull/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](https://github.com/zh-lx/pinyin-pro/pull/278)

## 3.25.0

- 【feat】Added `v` option to the `match` API to allow using `v` to match `ü` [#276](https://github.com/zh-lx/pinyin-pro/pull/276)

## 3.24.2

- 【feat】Added `rp` option to the `html` API to remove `<rp>(</rp>` and `<rp>)</rp>` from the output [#272](https://github.com/zh-lx/pinyin-pro/pull/272)
- 【feat】When the custom class name in the `html` API is set to `false` or `null`, the default class name is retained [#271](https://github.com/zh-lx/pinyin-pro/pull/271)

## 3.24.1

- 【fix】Fixed the issue where the `segment` function would discard the last punctuation mark [#268](https://github.com/zh-lx/pinyin-pro/pull/268)

## 3.24.0

- 【feat】Added `segment` API for word segmentation [#265](https://github.com/zh-lx/pinyin-pro/pull/265)
- 【feat】Added `nonZhScope` property to the `pinyin` API to specify the scope of `nonZh` [#266](https://github.com/zh-lx/pinyin-pro/pull/266)

## 3.23.1

- **patch**: Corrected some pronunciations [#260](https://github.com/zh-lx/pinyin-pro/pull/260)

## 3.23.0

- 【feat】Support for external calls to `getInitialAndFinal`, `getFinalParts`, `getNumOfTone`, and other APIs [#255](https://github.com/zh-lx/pinyin-pro/pull/255)

## 3.22.2

- 【fix】Fixed `.d.ts` file errors caused by alias [#253](https://github.com/zh-lx/pinyin-pro/pull/253)

## 3.22.1

- 【patch】Corrected some entries in the word library [#252](https://github.com/zh-lx/pinyin-pro/pull/252)
- 【perf】Slight performance optimization [#251](https://github.com/zh-lx/pinyin-pro/pull/251)

## 3.22.0

- 【feat】Comprehensive adaptation of all APIs to support double Unicode encoded Chinese characters [#242](https://github.com/zh-lx/pinyin-pro/pull/242), [#243](https://github.com/zh-lx/pinyin-pro/pull/243), [#247](https://github.com/zh-lx/pinyin-pro/pull/247)
- 【feat】Support for all characters in the [General Standard Chinese Character Table](https://zh.wiktionary.org/wiki/Appendix:%E6%B1%89%E8%AF%AD%E6%8B%BC%E9%9F%B3%E7%B4%A2%E5%BC%95/%E9%80%9A%E7%94%A8%E8%A7%84%E8%8C%83%E6%B1%89%E5%AD%97%E8%A1%A8) [#244](https://github.com/zh-lx/pinyin-pro/pull/244)
- 【feat】Support for the pronunciation of the repeated character 々 [#245](https://github.com/zh-lx/pinyin-pro/pull/245)
- 【feat】Support for pinyin characters like `êê̄ếê̌ề` [#248](https://github.com/zh-lx/pinyin-pro/pull/248)
- 【patch】Correct the default pronunciation of `曲`: [#249](https://github.com/zh-lx/pinyin-pro/pull/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](https://github.com/zh-lx/pinyin-pro/pull/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](https://zh.wiktionary.org/wiki/Appendix:%E2%80%9C%E4%B8%80%E2%80%9D%E5%8F%8A%E2%80%9C%E4%B8%8D%E2%80%9D%E7%9A%84%E5%8F%98%E8%B0%83)
- 【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

- 【patch】Updated some word libraries, see details: [2c2f57ad](https://github.com/zh-lx/pinyin-pro/commit/2c2f57ad039bf80de93e1156edaaa030a1d370a6), [cd8bdba5](https://github.com/zh-lx/pinyin-pro/commit/cd8bdba5e6d918e68facec835be396e2c4608d61), [e7a46dda](https://github.com/zh-lx/pinyin-pro/commit/e7a46dda4135da8b373aa72154c373951266e959)

## 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](https://github.com/zh-lx/pinyin-pro/issues/156)

## 3.19.3

- 【patch】Correct the directory：[434cf51cd](https://github.com/zh-lx/pinyin-pro/commit/434cf51cd7c7f2a50365bfbe142c70ca93bc2344)

## 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](https://github.com/zh-lx/pinyin-pro/pull/148)
- 【fix】<b>convert</b>: 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：

  ```
  只争朝夕: '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】<b>match</b>：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 to[863c2e9](https://github.com/zh-lx/pinyin-pro/commit/863c2e99e89a40fbf4d17d5b0449b1d7e7f309ec)

## 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](https://en.wikipedia.org/wiki/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】<b>pinyin</b>：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】<b>pinyin</b>：Fix the issue of duplicate pinyin when using `multiple: true` and `toneType: none` simultaneously in the `options` parameter

## 3.12.0

- 【feat】<b>pinyin</b>：`options.pattern` parameter adds optional values `finalHead`、`finalBody` and `finalTail`.
- 【feat】<b>pinyin</b>：`options.type` parameter adds optional value `all` to get all the data of Pinyin
- 【fix】<b>pinyin</b>：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】<b>match</b>：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】<b>pinyin</b>：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】<b>pinyin</b>：Fix again the issue of incorrect default values returned by double byte unicode encoded text

## 3.8.1

- 【fix】<b>pinyin</b>：Fix the issue of incorrect default values returned by double byte unicode encoded text

## 3.8.0

- 【feat】<b>pinyin</b>：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】<b>pinyin</b>：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】<b>pinyin</b>：Fix the issue of not prioritizing matching custom pinyin when using both the `customPinyin` API and `options.mode` is `surname` simultaneously.
- 【fix】<b>pinyin</b>：Fix the issue of incorrect pinyin for some surnames.

## 3.6.1

- 【fix】<b>pinyin</b>：Fix memory overflow when `options.removeNonZh` is `true` and all input strings are non Chinese Characters.

## 3.6.0

- 【feat】<b>pinyin</b>：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】<b>pinyin</b>：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】<b>pinyin</b>：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】<b>pinyin</b>：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】<b>pinyin</b>：`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

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

## Data Source

- More details on accuracy testing data: [accuracy](https://github.com/zh-lx/pinyin-pro/blob/main/packages/pinyin-pro/scripts/benchmark/accuracy.ts)
- More details on performance testing data: [speed](https://github.com/zh-lx/pinyin-pro/blob/main/packages/pinyin-pro/scripts/benchmark/speed.ts)

---

### 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
```

### Script Link

You can also import CDN files through the `<script />` tag to use it, taking two CDN manufacturers [unpkg](https://unpkg.com) and [jsDelivr](https://jsdelivr.com) as examples:

#### unpkg

```html

<head>
  <script src="https://unpkg.com/pinyin-pro@3.12.0/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/pinyin-pro@3.18.2/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'
});
```

### Script Link

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:

<div style="display: flex;">
  <img src="https://user-images.githubusercontent.com/73059627/226233976-5dbb9daa-6620-4d16-a2b0-359055dcafe1.png" width="200" >
  <img src="https://user-images.githubusercontent.com/73059627/226233691-848b2a40-f1a9-414e-a80f-3fc6c6209eb1.png" width="200" >
</div>

---

### 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.

<code-run></code-run>

---

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

# addDict <Badge type="tip" text="v3.20.0+" vertical="middle" />

`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](https://github.com/zh-lx/pinyin-pro/tree/main/packages/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 <Badge type="tip" text="v3.17.0+" vertical="middle" />

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)：<b>string | string[]</b>, the pinyin string or array of pinyin strings to convert
- `options` (optional): <b>object</b>, the configuration of conversion rules：

<table>
    <tr>
        <th>Attribute</th>
        <th>Type</th>
        <th>Description</th>
        <th>Optional Values</th>
        <th>Detail</th>
        <th width="100">Default Value</th>
    </tr>
    <tr>
        <td>separator</td>
        <td>string</td>
        <td>the separator specified</td>
        <td>-</td>
        <td>convert function will split pinyin with this separator for conversion</td>
        <td><code>' '</code></td>
    </tr>
    <tr>
        <td rowspan="3">format</td>
        <td rowspan="3">string</td>
        <td rowspan="3">format of conversion</td>
        <td>numToSymbol</td>
        <td>convert number to symbol</td>
        <td rowspan="3">numToSymbol</td>
    </tr>
    <tr>
        <td>SymbolToNum</td>
        <td>convert symbol to number</td>
    </tr>
    <tr>
        <td>toneNone</td>
        <td>remove symbol in pinyin</td>
    </tr>
</table>

---

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

# customPinyin <Badge type="tip" text="v3.4.0+" vertical="middle" />

`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` <Badge type="tip" text="v3.19.0+" vertical="middle" />

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 <Badge type="tip" text="v3.19.0+" vertical="middle" />

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): <b>object</b>, customized pinyin mapping, where key is a Chinese character and value is pinyin.
- `options` (optional): <b>object</b>, 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 <Badge type="tip" text="v3.15.0+" vertical="middle" />

Use `html` API to get a HTML string of Chinese characters and Pinyin in the format of '<ruby></ruby>'.

## 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 `<span class="py result item"></span>` 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 `<span class="py-chinese-item"></span>` 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 `<span class="py non Chinese item"></span>` 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:

<html-basic-demo></html-basic-demo>

### 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:

<html-no-tone-demo></html-no-tone-demo>

### 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:

<html-style-demo></html-style-demo>

### 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:

<html-custom-class-demo></html-custom-class-demo>

## 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): <b>string</b>, the Chinese character string to convert.
- `options` (optional): <b>object</b>, the configuration related to the return value, more specific information is shown in the table below：

<table>
    <tr>
        <th>Key</th>
        <th>Type</th>
        <th>Description</th>
        <th>Optional Values</th>
        <th width="180">Default Value</th>
    </tr>
    <tr>
        <td>resultClass</td>
        <td>string</td>
        <td>class of the outermost <code>&lt;span&gt;</code> tag of Chinese characters and pinyin</td>
        <td>-</td>
        <td>py-result-item</td>
    </tr>
    <tr>
        <td>pinyinClass</td>
        <td>string</td>
        <td>class of the outer <code>&lt;rt&gt;</code> tag of Pinyin</td>
        <td>-</td>
        <td>py-pinyin-item</td>
    </tr>
    <tr>
        <td>chineseClass</td>
        <td>string</td>
        <td>class of the outer <code>&lt;span&gt;</code> tag of Chinese character</td>
        <td>-</td>
        <td>py-chinese-item</td>
    </tr>
    <tr>
        <td>wrapNonChinese</td>
        <td>string</td>
        <td>Whether use <code>&lt;span&gt;</code> 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 <code>true</code>; If the input text parameter is also an HTML string, it is recommended to set it to <code>false</code> to prevent affecting the structure of the text.</td>
        <td><code>true/false</code></td>
        <td>false</td>
    </tr>
    <tr>
        <td>nonChineseClass</td>
        <td>string</td>
        <td>class of the outer <code>&lt;span&gt;</code> tag of non Chinese character(Only when the value of <code>wrapNonChinese</code> is <code>true</code>, it is work.)</td>
        <td>-</td>
        <td>py-non-chinese-item</td>
    </tr>
    <tr>
        <td>toneType</td>
        <td>string</td>
        <td>the display form of tones in Pinyin</td>
        <td><code>symbol/none/num</code></td>
        <td>symbol</td>
    </tr>
</table>

---

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

# match <Badge type="tip" text="v3.15.0+" vertical="middle" />

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 ü <Badge type="tip" text="v3.25.0+" vertical="middle" />

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)：<b>string</b>, Chinese text to match
- `pinyin` (required)：<b>string</b>, Pinyin to match
- `options` (optional): <b>object</b>, the configuration of matching rules, more specific information is shown in the table below：

<table>
    <tr>
        <th>Attribute</th>
        <th>Type</th>
        <th>Description</th>
        <th>Optional Values</th>
        <th>Detail</th>
        <th width="100">Default Value</th>
    </tr>
    <tr>
        <td rowspan="4">precision</td>
        <td rowspan="4">string</td>
        <td rowspan="4">matching accuracy</td>
        <td>first</td>
        <td>matching is considered successful when the initial letter or full pinyin is equal to the current pinyin</td>
        <td rowspan="4">first</td>
    </tr>
    <tr>
        <td>start</td>
        <td>starting with the current pinyin is considered a successful match</td>
    </tr>
    <tr>
        <td>every</td>
        <td>full Pinyin and current Pinyin are strictly equal in order to be considered a successful match</td>
    </tr>
    <tr>
        <td>any</td>
        <td>containing all characters of the current pinyin are considered as successful matches</td>
    </tr>
    <tr>
        <td rowspan="2">continuous</td>
        <td rowspan="2">boolean</td>
        <td rowspan="2">Whether the matching Chinese indexes need to be continuous in order to be considered successful</td>
        <td>true</td>
        <td>not required</td>
        <td rowspan="2">false</td>
    </tr>
    <tr>
        <td>false</td>
        <td>required</td>
    </tr>
    <tr>
        <td rowspan="2">space</td>
        <td rowspan="2">string</td>
        <td rowspan="2">handling of spaces in Chinese characters and pinyin during matching</td>
        <td>ignore</td>
        <td>ignore</td>
        <td rowspan="2">ignore</td>
    </tr>
    <tr>
        <td>preserve</td>
        <td>preserve</td>
    </tr>
    <tr>
        <td rowspan="4">lastPrecision</td>
        <td rowspan="4">string</td>
        <td rowspan="4">the accuracy of the last character matching</td>
        <td>first</td>
        <td>Matching is considered successful when the initial letter or full pinyin is equal to the current pinyin</td>
        <td rowspan="4">By default, when the <code>precision</code> is <code>any</code>, <code>lastPrecision</code> is <code>any</code>; Otherwise <code>lastPrecision</code> is <code>start</code></td>
    </tr>
    <tr>
        <td>start</td>
        <td>starting with the current pinyin is considered a successful match</td>
    </tr>
    <tr>
        <td>every</td>
        <td>full Pinyin and current Pinyin are strictly equal in order to be considered a successful match</td>
    </tr>
    <tr>
        <td>any</td>
        <td>containing all characters of the current pinyin are considered as successful matches</td>
    </tr>
    <tr>
        <td rowspan="2">v</td>
        <td rowspan="2">boolean</td>
        <td rowspan="2">Whether to allow using <code>v</code> to match <code>ü</code></td>
        <td>true</td>
        <td>allow using <code>v</code> to match <code>ü</code></td>
        <td rowspan="2">false</td>
    </tr>
    <tr>
        <td>false</td>
        <td>not allow using <code>v</code> to match <code>ü</code></td>
    </tr>
</table>

---

### 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 <Badge type="tip" text="v3.12.0+" vertical="middle" />

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 <Badge type="tip" text="v3.1.0+" vertical="middle" />

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 <Badge type="tip" text="v3.12.0+" vertical="middle" />

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 <Badge type="tip" text="v3.21.0+" vertical="middle" />

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 <Badge type="tip" text="v3.16.0+" vertical="middle" />

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 <Badge type="tip" text="v3.8.0+" vertical="middle" />

`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` <Badge type="tip" text="v3.9.0+" vertical="middle" />

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 <Badge type="tip" text="v3.20.0+" vertical="middle" />

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 <Badge type="tip" text="v3.27.0+" vertical="middle" />

According to [wiki](https://zh.wikipedia.org/zh-cn/%E6%B1%89%E8%AF%AD%E6%8B%BC%E9%9F%B3#%E5%A3%B0%E6%AF%8D), `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)：<b>string</b>, string that needs to be converted to pinyin
- `options` (optional)：<b>object</b>, content and format of the output. For more detailed information, please refer to the table below

<basic-params-table></basic-params-table>

---

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

# polyphonic <Badge type="tip" text="v3.15.0+" vertical="middle" />

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

::: tip
In most cases, you only need to use the [pinyin](/use/pinyin.md) 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：

```
/* 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

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

---

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

# Segment <Badge type="tip" text="v3.24.0+" vertical="middle" />

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 <Badge type="tip" text="v3.28.0+" vertical="middle" />

`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`

```
/* 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 后的体积。

<table>
    <thead>
        <tr>
            <th>API</th>
            <th>ESM</th>
            <th>UMD</th>
        </tr>
    </thead>
    <tbody>
    <tr><td>pinyin</td><td>307.03 KB (gzip 134.83 KB)</td><td rowspan="7">317.47 KB (gzip 138.33 KB)</td></tr>
    <tr><td>segment</td><td>305.79 KB (gzip 134.04 KB)</td></tr>
    <tr><td>match</td><td>185.67 KB (gzip 80.90 KB)</td></tr>
    <tr><td>convert</td><td>1.78 KB (gzip 0.98 KB)</td></tr>
    <tr><td>html</td><td>307.87 KB (gzip 135.13 KB)</td></tr>
    <tr><td>polyphonic</td><td>180.75 KB (gzip 78.83 KB)</td></tr>
    <tr><td>总体积</td><td>561.18 KB (gzip 158.13 KB)</td></tr>
    </tbody>
</table>

---

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

# 更新日志

## 3.29.5

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

## 3.29.4

- 【fix】兼容 Cloudflare Workers 等运行时在模块初始化阶段禁用定时器的限制 [#364](https://github.com/zh-lx/pinyin-pro/pull/364)
- 【perf】`match`: 优化 DP 过程中的重复计算以及内存占用 [#362](https://github.com/zh-lx/pinyin-pro/pull/362)、[#360](https://github.com/zh-lx/pinyin-pro/pull/360)
- 【perf】`segmentit`: Node 环境下不再通过 `setTimeout` 预构建 AC 自动机，进一步降低 `import` 开销 [#361](https://github.com/zh-lx/pinyin-pro/pull/361)

## 3.29.3

感谢 [@luojiyin1987](https://github.com/luojiyin1987) 对分词模块的持续优化，`pinyin` API 性能进一步提升(约 20%+):
- 【perf】`segmentit`: 构建 AC 自动机时避免 `prefix` 字符串分配 [#344](https://github.com/zh-lx/pinyin-pro/pull/344)
- 【perf】`segmentit`: 复用 AC 匹配过程中的子节点查找 [#346](https://github.com/zh-lx/pinyin-pro/pull/346)
- 【perf】`segmentit`: 使用回溯指针重建最大概率路径 [#348](https://github.com/zh-lx/pinyin-pro/pull/348)
- 【perf】`splitString`: 对 BMP 文本走原生 `split` 快路径 [#349](https://github.com/zh-lx/pinyin-pro/pull/349)
- 【perf】`pinyin`: 文本不含 `々` 时跳过叠字处理器 [#351](https://github.com/zh-lx/pinyin-pro/pull/351)

## 3.29.2

感谢 [@luojiyin1987](https://github.com/luojiyin1987) 的一系列优化，`pinyin` API 性能得到显著提升(约30%+):
- 【perf】`pinyin`: 在所有输出模式中复用解析后的 `final` [#342](https://github.com/zh-lx/pinyin-pro/pull/342)
- 【fix】`customPinyin`: 防止更新时 `pattern` 重复积累 [#340](https://github.com/zh-lx/pinyin-pro/pull/340)
- 【perf】`pinyin`: 在多个 `middleware` 中复用分割后的字符 [#338](https://github.com/zh-lx/pinyin-pro/pull/338)
- 【perf】`pinyin`: 避免非多音字拼音被 `split` 分割 [#336](https://github.com/zh-lx/pinyin-pro/pull/336)

## 3.29.1

- 【perf】推迟 AC 自动机的构建时机，减少 `import pinyin-pro` 时对主线程的阻塞 [#333](https://github.com/zh-lx/pinyin-pro/pull/333)
- 【perf】优化 `middlewareMultiple` 重复计算的问题 [#330](https://github.com/zh-lx/pinyin-pro/pull/330)
- 【fix】修复 `nonZhScope` 非中文字符移除不彻底的问题 [#329](https://github.com/zh-lx/pinyin-pro/pull/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](https://github.com/zh-lx/pinyin-pro/pull/323)
- 【perf】优化 ESM 打包配置，确保 tree shaking 时仅引入必要代码，减小各个 API 的 size [#327](https://github.com/zh-lx/pinyin-pro/pull/327)

## 3.28.2

- 【patch】词库修正以下词语：

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

## 3.28.1

- 【feat】`convert` api 中增加了对于儿化音缩写格式的识别支持 [#306](https://github.com/zh-lx/pinyin-pro/pull/306)

## 3.28.0

- 【feat】新增 `addTraditionalDict` API，用于更好的识别繁体字 [#303](https://github.com/zh-lx/pinyin-pro/pull/303)

## 3.27.0

- 【feat】`pinyin` API 新增 `initialPattern` 选项，用于排除 `y` 和 `w` 作为声母 [#295](https://github.com/zh-lx/pinyin-pro/pull/295)

## 3.26.0

- 【feat】修复 `first` 在 `pattern: 'first'` 模式和 `type: 'all'` 中返回值不一致的问题：修改为对于非中文，统一返回原始非中文字符 [#278](https://github.com/zh-lx/pinyin-pro/pull/278)

## 3.25.0

- 【feat】`match` API 新增 `v` 选项，允许使用 `v` 匹配 `ü` 的拼音 [#276](https://github.com/zh-lx/pinyin-pro/pull/276)

## 3.24.2

- 【feat】`html` API 增加 `rp` 选项，用于去除输出结果中的 `<rp>(</rp>` 和 `<rp>)</rp>` [#272](https://github.com/zh-lx/pinyin-pro/pull/272)
- 【feat】`html` API 中自定义类名为 `false` 或者 `null` 时，保持默认类名 [#271](https://github.com/zh-lx/pinyin-pro/pull/271)

## 3.24.1

- 【fix】修复 `segment` 对于最后的标点符号丢弃的问题 [#268](https://github.com/zh-lx/pinyin-pro/pull/268)

## 3.24.0

- 【feat】新增 `segment` API 用于分词 [#265](https://github.com/zh-lx/pinyin-pro/pull/265)
- 【feat】`pinyin` API 新增 `nonZhScope` 属性用于指定 `nonZh` 的范围 [#266](https://github.com/zh-lx/pinyin-pro/pull/266)

## 3.23.1

- 【patch】修正部分读音 [#260](https://github.com/zh-lx/pinyin-pro/pull/260)

## 3.23.0

- 【feat】支持外部调用 `getInitialAndFinal`、`getFinalParts`、`getNumOfTone` 等 API [#255](https://github.com/zh-lx/pinyin-pro/pull/255)

## 3.22.2

- 【fix】修复 alias 导致的 `.d.ts` 文件报错 [#253](https://github.com/zh-lx/pinyin-pro/pull/253)

## 3.22.1

- 【patch】校正部分词库 [#252](https://github.com/zh-lx/pinyin-pro/pull/252)
- 【perf】小幅优化性能 [#251](https://github.com/zh-lx/pinyin-pro/pull/251)

## 3.22.0

- 【feat】各 api 全面适配双 unicode 编码中文字符 [#242](https://github.com/zh-lx/pinyin-pro/pull/242)、[#243](https://github.com/zh-lx/pinyin-pro/pull/243)、[#247](https://github.com/zh-lx/pinyin-pro/pull/247)
- 【feat】支持[《通用汉字规范表》](https://zh.wiktionary.org/wiki/Appendix:%E6%B1%89%E8%AF%AD%E6%8B%BC%E9%9F%B3%E7%B4%A2%E5%BC%95/%E9%80%9A%E7%94%A8%E8%A7%84%E8%8C%83%E6%B1%89%E5%AD%97%E8%A1%A8) 中所有字符 [#244](https://github.com/zh-lx/pinyin-pro/pull/244)
- 【feat】支持叠字符 々 的发音 [#245](https://github.com/zh-lx/pinyin-pro/pull/245)
- 【feat】支持 `êê̄ếê̌ề` 等拼音字符 [#248](https://github.com/zh-lx/pinyin-pro/pull/248)
- 【patch】修正 `曲` 默认读音: [#249](https://github.com/zh-lx/pinyin-pro/pull/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](https://github.com/zh-lx/pinyin-pro/pull/232)

## 3.20.2

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

## 3.20.1

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

## 3.20.0

- 【feat】支持通过 `addDict` api 自定义词典
- 【feat】增加 `一` 和 `不` 的变调智能识别，可通过 `toneSandhi` 参数控制开启和关闭,参考: [维基百科](https://zh.wiktionary.org/wiki/Appendix:%E2%80%9C%E4%B8%80%E2%80%9D%E5%8F%8A%E2%80%9C%E4%B8%8D%E2%80%9D%E7%9A%84%E5%8F%98%E8%B0%83)
- 【feat】增加 `行`、`斗`、`重` 前面跟数量词时的发音智能识别
- 【feat】增加 `了` 在起始的发音智能识别
- 【feat】html api 增加 `customClassMap` 选项用于对指定字增加自定义类名
- 【feat】应用了新的分词算法，支持传入词典，分词更加准确
- 【feat】`all` 模式新增 `polyphonic` 和 `inZhRange` 属性
- 【fix】修复了使用 `customPinyin` api 时的效率低下的问题
- 【fix】修复 `multiple` 和 `surname` 一同使用的部分问题
- 【fix】修复 `multiple` 模式只有一个非中文时丢失该字符的问题
- 【patch】校正部分词语的拼音

## 3.19.6

- 【patch】更新部分词库，详见：[2c2f57ad](https://github.com/zh-lx/pinyin-pro/commit/2c2f57ad039bf80de93e1156edaaa030a1d370a6)、[cd8bdba5](https://github.com/zh-lx/pinyin-pro/commit/cd8bdba5e6d918e68facec835be396e2c4608d61)、[e7a46dda](https://github.com/zh-lx/pinyin-pro/commit/e7a46dda4135da8b373aa72154c373951266e959)

## 3.19.5

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

## 3.19.4

- 【fix】修复非中文字符在 `toneType: none` 参数下转换错误的问题 [#156](https://github.com/zh-lx/pinyin-pro/issues/156)

## 3.19.3

- 【patch】词库修正：[434cf51cd](https://github.com/zh-lx/pinyin-pro/commit/434cf51cd7c7f2a50365bfbe142c70ca93bc2344)

## 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](https://github.com/zh-lx/pinyin-pro/pull/148)
- 【fix】<b>convert</b>：支持 `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】词库修正以下词语

  ```
  只争朝夕: '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】<b>match</b>：`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](https://github.com/zh-lx/pinyin-pro/commit/863c2e99e89a40fbf4d17d5b0449b1d7e7f309ec)

## 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 自动机算法](https://en.wikipedia.org/wiki/Aho–Corasick_algorithm)优化拼音匹配速度，性能提升近 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】<b>pinyin</b>：修复 options 参数 `multiple` 与 `surname` 同时使用时冲突问题
- 【patch】修正部分儿化字读音

## 3.13.0

- 【fix】<b>pinyin</b>：修复 options 参数 `multiple: true` 和 `toneType: 'none'` 同时使用时，可能存在重复拼音的问题

## 3.12.0

- 【feat】<b>pinyin</b>：`options.pattern` 参数新增可选值获取韵头(`finalHead`)、韵腹(`finalBody`)、韵尾(`finalTail`)的功能。 [去看看](/use/pinyin.html#韵头-介音-韵腹-韵尾)
- 【feat】<b>pinyin</b>：`options.type` 参数新增可选值 `all` 获取拼音相关完整的信息。 [去看看](/use/pinyin.html#完整内容)
- 【fix】<b>pinyin</b>：修复 `text` 参数中包含空格且 `options.type` 参数为 `array` 时输出结果错误的问题

## 3.11.0

- 【perf】优化拼音词库，提升拼音识别准确率
- 【perf】包体积优化约 10%
- 【feat】<b>match</b>：新增支持中文匹配、中文及拼音混合匹配

## 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】<b>pinyin</b>：`options` 参数增加 `v` 可选属性，`options.v = true` 可将拼音中的 `ü` 替换为 `v`。[去看看](/use/pinyin.html#拼音-u-替换为-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】<b>pinyin</b>：再次修复双字节 unicode 编码的文字返回默认值不正确的问题

## 3.8.1

- 【fix】<b>pinyin</b>：修复双字节 unicode 编码的文字返回默认值不正确的问题

## 3.8.0

- 【feat】<b>pinyin</b>：`options` 参数新增 `nonZh` 可选属性，用于配置非中文字符串的输出规则。[去看看](/use/pinyin.html#非汉字字符处理)

## 3.7.2

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

## 3.7.1

- 【fix】<b>pinyin</b>：修复 “嗯” 在 `options.toneType = none` 时拼音转换错误的问题

## 3.7.0

- 【perf】支持 esm 动态引入

## 3.6.2

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

## 3.6.1

- 【fix】<b>pinyin</b>：修复 `options.removeNonZh = true` 且输入字符串全部为非汉字时的内存溢出问题

## 3.6.0

- 【feat】<b>pinyin</b>：`options` 参数新增 `removeNonZh` 可选属性，为 `options.removeNonZh = true` 时移除非汉字的字符

## 3.5.0

- 【feat】新增 `match` api 以支持拼音文本匹配功能。[去看看](/use/match)

## 3.4.1

- 【fix】<b>pinyin</b>：修复 `options.pattern = 'first'` 或者 `options.pattern = 'initial'` 时，指定 `options.toneType = 'num'` 获取音调失效的问题

## 3.4.0

- 【feat】<b>pinyin</b>：`options` 参数新增 `mode` 可选属性，`options.mode = 'surname'` 模式支持姓氏模式拼音识别。[去看看](/use/pinyin.html#姓氏模式)
- 【feat】新增 `customPinyin` api，支持用户自定义拼音功能。[去看看](/use/customPinyin)
- 【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】<b>pinyin</b>：修复 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】<b>pinyin</b>：`options.pattern` 新增 `first` 可选值[获取拼音首字母](/use/pinyin.html#首字母)
- 【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

## 对比结果

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

## 基准数据

- 准确率测试数据可见: [accuracy](https://github.com/zh-lx/pinyin-pro/blob/main/packages/pinyin-pro/scripts/benchmark/accuracy.ts)
- 性能测试数据可见：[speed](https://github.com/zh-lx/pinyin-pro/blob/main/packages/pinyin-pro/scripts/benchmark/speed.ts)

---

### 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](https://unpkg.com) 和 [jsDelivr](https://jsdelivr.com) CDN 厂商为例：

#### unpkg

```html

<head>
  <script src="https://unpkg.com/pinyin-pro@3.18.2/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/pinyin-pro@3.18.2/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` 进行咨询与反馈:

<div style="display: flex;">
  <img src="https://user-images.githubusercontent.com/73059627/226233976-5dbb9daa-6620-4d16-a2b0-359055dcafe1.png" width="200" >
  <img src="https://user-images.githubusercontent.com/73059627/226233691-848b2a40-f1a9-414e-a80f-3fc6c6209eb1.png" width="200" >
</div>

---

### Packages Docs Zh Docs Run Run (`packages/docs/zh/docs/run/run.md`)

# 在线运行

已自动从 `pinyin-pro` 中引入 `pinyin`、`match`、`html`、`polyphonic` 和 `customPinyin` 等 API，无需手动引入。

<code-run></code-run>

---

### Packages Docs Zh Docs Use AddDict (`packages/docs/zh/docs/use/addDict.md`)

# addDict <Badge type="tip" text="v3.20.0+" vertical="middle" />

`pinyin-pro` 内置了一些高频常用词的词典，想要保证高准确率，需要应用更完备的词典，可以通过 `addDict` 添加词典。详见 [@pinyin-pro/data](https://github.com/zh-lx/pinyin-pro/tree/main/packages/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 <Badge type="tip" text="v3.17.0+" vertical="middle" />

`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 类型，转换规则的配置，详细见下表：

<table>
    <tr>
        <th>属性</th>
        <th>类型</th>
        <th>描述</th>
        <th>可选值</th>
        <th>说明</th>
        <th width="100">默认值</th>
    </tr>
    <tr>
        <td>separator</td>
        <td>string</td>
        <td>指定的分隔符</td>
        <td>-</td>
        <td>convert 方法会以该分隔符分割拼音进行转换</td>
        <td><code>' '</code></td>
    </tr>
    <tr>
        <td rowspan="3">format</td>
        <td rowspan="3">string</td>
        <td rowspan="3">转换的格式</td>
        <td>numToSymbol</td>
        <td>将拼音数字转换为带符号的拼音</td>
        <td rowspan="3">numToSymbol</td>
    </tr>
    <tr>
        <td>SymbolToNum</td>
        <td>将带符号的拼音转换为拼音数字</td>
    </tr>
    <tr>
        <td>toneNone</td>
        <td>将带符号的拼音转换为无符号拼音</td>
    </tr>
</table>

---

### Packages Docs Zh Docs Use CustomPinyin (`packages/docs/zh/docs/use/customPinyin.md`)

# customPinyin <Badge type="tip" text="v3.4.0+" vertical="middle" />

`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 生效 <Badge type="tip" text="v3.19.0+" vertical="middle" />

通过在 `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"]
```

### 清除原自定义的数据 <Badge type="tip" text="v3.19.0+" vertical="middle" />

默认情况下，多次调用 `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 <Badge type="tip" text="v3.15.0+" vertical="middle" />

使用 `html` api 获取`<ruby></ruby>` 格式的汉字和拼音 HTML 字符串。

## 示例

### 常规使用

`html` api 返回值为 HTML 格式的字符串：

- 每个汉字和拼音最外层是由一个 `<span class="py-result-item"></span>` 标签包裹(可以通过 `resultClass` 属性自定义该标签的类名)
- 内层是 `<ruby></ruby>` 标签用于展示汉字和拼音
- 汉字部分由 `<span class="py-chinese-item"></span>` 标签包裹(可以通过 `chineseClass` 属性自定义该标签的类名)
- 拼音部分由 `<rt class="py-pinyin-item"></rt>` 标签包裹(可以通过 `pinyinClass` 属性自定义该标签的类名)
- 默认情况下，非汉字没有标签包裹。通过设置 `wrapNonChinese` 属性的值为 `true`，非汉字部分会被 `<span class="py-non-chinese-item"></span>` 标签包裹。(可以通过 `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` 字符串在浏览器中的预览效果如下：

<html-basic-demo></html-basic-demo>

### 不带音调

当设置 `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-no-tone-demo></html-no-tone-demo>

### 自定义样式

可以通过 `html` api 返回值中的类名来控制具体的样式，如下面的例子中，我们让汉字部分为蓝色，拼音部分为红色。

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

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

```css
/* css */
.py-chinese-item {
  color: blue;
}
.py-pinyin-item {
  color: red;
}
```

在浏览器中的预览效果：

<html-style-demo></html-style-demo>

### 指定文字样式

可以通过 `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;
}
```

在浏览器中的预览效果：

<html-custom-class-demo></html-custom-class-demo>

## 语法及参数

### 语法

```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 类型，返回值相关的配置，具体如下表：

<table>
    <tr>
        <th>属性</th>
        <th>类型</th>
        <th>描述</th>
        <th>可选值</th>
        <th width="180">默认值</th>
    </tr>
    <tr>
        <td>resultClass</td>
        <td>string</td>
        <td>汉字和拼音最外层 <code>&lt;span&gt;</code> 标签的类名</td>
        <td>-</td>
        <td>py-result-item</td>
    </tr>
    <tr>
        <td>pinyinClass</td>
        <td>string</td>
        <td>拼音外层 <code>&lt;rt&gt;</code> 标签的类名</td>
        <td>-</td>
        <td>py-pinyin-item</td>
    </tr>
    <tr>
        <td>chineseClass</td>
        <td>string</td>
        <td>汉字外层 <code>&lt;span&gt;</code> 标签的类名</td>
        <td>-</td>
        <td>py-chinese-item</td>
    </tr>
    <tr>
        <td>wrapNonChinese</td>
        <td>boolean</td>
        <td>是否用 <code>&lt;span&gt;</code> 标签包裹非汉字字符。如果是要对非汉字字符也做一些自定义样式处理，建议设置为 <code>true</code>; 如果 text 参数本身也是一个 HTML 字符串，建议设置为 <code>false</code> 以防止影响 text 本身的结构</td>
        <td><code>true/false</code></td>
        <td>false</td>
    </tr>
    <tr>
        <td>nonChineseClass</td>
        <td>string</td>
        <td>非汉字字符外层 <code>&lt;span&gt;</code> 标签的类名（仅在 <code>wrapNonChinese</code> 值为 <code>true</code> 时有效）</td>
        <td>-</td>
        <td>py-non-chinese-item</td>
    </tr>
    <tr>
        <td>toneType</td>
        <td>string</td>
        <td>拼音中音调的显示形式</td>
        <td><code>symbol/none/num</code></td>
        <td>symbol</td>
    </tr>
</table>

---

### Packages Docs Zh Docs Use Match (`packages/docs/zh/docs/use/match.md`)

# match <Badge type="tip" text="v3.15.0+" vertical="middle" />

`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` 匹配 `ü` <Badge type="tip" text="v3.25.0+" vertical="middle" />

通过指定 `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 类型，匹配规则的配置，详细见下表：

<table>
    <tr>
        <th>属性</th>
        <th>类型</th>
        <th>描述</th>
        <th>可选值</th>
        <th>说明</th>
        <th width="100">默认值</th>
    </tr>
    <tr>
        <td rowspan="4">precision</td>
        <td rowspan="4">string</td>
        <td rowspan="4">匹配的精度</td>
        <td>first</td>
        <td>首字母或者全拼和当前拼音相等即为匹配成功</td>
        <td rowspan="4">first</td>
    </tr>
    <tr>
        <td>start</td>
        <td>以当前拼音为开头即为匹配成功</td>
    </tr>
    <tr>
        <td>every</td>
        <td>全拼和当前拼音严格相等才算匹配成功</td>
    </tr>
    <tr>
        <td>any</td>
        <td>包含当前拼音的所有字符即为匹配成功</td>
    </tr>
    <tr>
        <td rowspan="2">continuous</td>
        <td rowspan="2">boolean</td>
        <td rowspan="2">匹配的汉字下标是否需要为连续的才算匹配成功</td>
        <td>true</td>
        <td>不需要</td>
        <td rowspan="2">false</td>
    </tr>
    <tr>
        <td>false</td>
        <td>需要</td>
    </tr>
    <tr>
        <td rowspan="2">space</td>
        <td rowspan="2">string</td>
        <td rowspan="2">匹配时对于汉字和拼音中空格的处理</td>
        <td>ignore</td>
        <td>忽略</td>
        <td rowspan="2">ignore</td>
    </tr>
    <tr>
        <td>preserve</td>
        <td>保留</td>
    </tr>
    <tr>
        <td rowspan="4">lastPrecision</td>
        <td rowspan="4">string</td>
        <td rowspan="4">最后一个字符匹配的精度</td>
        <td>first</td>
        <td>首字母或者全拼和当前拼音相等即为匹配成功</td>
        <td rowspan="4">当 <code>precision</code> 为 <code>any</code> 时，<code>lastPrecision</code> 默认为 <code>any</code>；其他情况下 <code>lastPrecision</code> 默认为 <code>start</code></td>
    </tr>
    <tr>
        <td>start</td>
        <td>以当前拼音为开头即为匹配成功</td>
    </tr>
    <tr>
        <td>every</td>
        <td>全拼和当前拼音严格相等才算匹配成功</td>
    </tr>
    <tr>
        <td>any</td>
        <td>包含当前拼音的所有字符即为匹配成功</td>
    </tr>
    <tr>
        <td rowspan="2">v</td>
        <td rowspan="2">boolean</td>
        <td rowspan="2">是否允许使用 <code>v</code> 匹配 <code>ü</code></td>
        <td>true</td>
        <td>允许使用 <code>v</code> 匹配 <code>ü</code></td>
        <td rowspan="2">false</td>
    </tr>
    <tr>
        <td>false</td>
        <td>不允许使用 <code>v</code> 匹配 <code>ü</code></td>
    </tr>
</table>

---

### 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']
```

### 韵头(介音)/韵腹/韵尾 <Badge type="tip" text="v3.12.0+" vertical="middle" />

设置 `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"]
```

### 首字母 <Badge type="tip" text="v3.1.0+" vertical="middle" />

设置 `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']
```

### 完整内容 <Badge type="tip" text="v3.12.0+" vertical="middle" />

设置 `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é
```

### 姓氏模式 <Badge type="tip" text="v3.21.0+" vertical="middle" />

设置 `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è'
```

### 自定义分隔符 <Badge type="tip" text="v3.16.0+" vertical="middle" />

使用 `options.separator` 自定义拼音之间的分隔符，仅在 `type: 'string'` 时生效：

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

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

### 非汉字字符处理 <Badge type="tip" text="v3.8.0+" vertical="middle" />

设置 `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 <Badge type="tip" text="v3.9.0+" vertical="middle" />

设置 `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
```

### 选择不同的分词算法 <Badge type="tip" text="v3.20.0+" vertical="middle" />

设置 `options.segmentit` 以选择不同的分词算法，默认为最大概率算法：

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

// 逆向最大匹配算法：速度最快
pinyin('小明硕士毕业于中国科学院计算所，后在日本京都大学深造', {
  segmentit: 1,
});

// 最大概率算法：识别最准确
pinyin('小明硕士毕业于中国科学院计算所，后在日本京都大学深造', {
  segmentit: 2,
});

// 最少分词数算法
pinyin('小明硕士毕业于中国科学院计算所，后在日本京都大学深造', {
  segmentit: 3,
});
```

### 声母排除 y 和 w <Badge type="tip" text="v3.27.0+" vertical="middle" />

根据 [wiki](https://zh.wikipedia.org/zh-cn/%E6%B1%89%E8%AF%AD%E6%8B%BC%E9%9F%B3#%E5%A3%B0%E6%AF%8D)，`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 类型，转换输出的内容及格式，详细见下表

<basic-params-table></basic-params-table>

---

### Packages Docs Zh Docs Use Polyphonic (`packages/docs/zh/docs/use/polyphonic.md`)

# polyphonic <Badge type="tip" text="v3.15.0+" vertical="middle" />

使用 `polyphonic` api 来获取多音字的全部读音。

::: tip
大多数情况下你只需要使用 [pinyin](/use/pinyin.md) api，它会自动识别文本中多音字的正确读音。`polyphonic` 是用来获取每个字的所有读音的而不是多音字在句子中的正确读音。
:::

## 示例

### 常规使用

使用 `type` 属性控制返回值的格式：

```
/* 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[][]
```

### 参数

<table>
    <tr>
        <th>属性</th>
        <th>类型</th>
        <th>描述</th>
        <th>可选值</th>
        <th>说明</th>
        <th width="100">默认值</th>
    </tr>
    <tr>
        <td rowspan="3">type</td>
        <td rowspan="3">string</td>
        <td rowspan="3">返回的格式</td>
        <td>string</td>
        <td>string 数组</td>
        <td rowspan="3">string</td>
    </tr>
    <tr>
        <td>array</td>
        <td>string 二维数组</td>
    </tr>
    <tr>
        <td>all</td>
        <td>AllData 类型二维数组</td>
    </tr>
    <tr>
        <td rowspan="3">toneType</td>
        <td rowspan="3">string</td>
        <td rowspan="3">音调展示的形式</td>
        <td>symbol</td>
        <td>正常拼音音调</td>
        <td rowspan="3">symbol</td>
    </tr>
    <tr>
        <td>none</td>
        <td>不展示</td>
    </tr>
    <tr>
        <td>num</td>
        <td>跟在拼音后以数字展示</td>
    </tr>
    <tr>
        <td rowspan="8">pattern</td>
        <td rowspan="8">string</td>
        <td rowspan="8">展示的内容</td>
        <td>pinyin</td>
        <td>拼音全拼</td>
        <td rowspan="8">pinyin</td>
    </tr>
    <tr>
        <td>initial</td>
        <td>声母</td>
    </tr>
    <tr>
        <td>final</td>
        <td>韵母</td>
    </tr>
    <tr>
        <td>num</td>
        <td>音调对应数字</td>
    </tr>
    <tr>
        <td>first</td>
        <td>首字母</td>
    </tr>
    <tr>
        <td>finalHead</td>
        <td>韵头</td>
    </tr>
    <tr>
        <td>finalBody</td>
        <td>韵腹</td>
    </tr>
    <tr>
        <td>finalTail</td>
        <td>韵尾</td>
    </tr>
    <tr>
        <td rowspan="3">nonZh</td>
        <td rowspan="3">string</td>
        <td rowspan="3">非中文字符处理</td>
        <td>spaced</td>
        <td>空格间隔开</td>
        <td rowspan="3">spaced</td>
    </tr>
    <tr>
        <td>consecutive</td>
        <td>连续</td>
    </tr>
    <tr>
        <td>removed</td>
        <td>从返回值中移除</td>
    </tr>
    <tr>
        <td rowspan="2">v</td>
        <td rowspan="2">boolean</td>
        <td rowspan="2">是否使用<code>v</code>替换返回值中的<code>ü</code></td>
        <td>false</td>
        <td>不替换</td>
        <td rowspan="2">false</td>
    </tr>
    <tr>
        <td>true</td>
        <td>替换</td>
    </tr>
</table>

---

### Packages Docs Zh Docs Use Segment (`packages/docs/zh/docs/use/segment.md`)

# segment <Badge type="tip" text="v3.24.0+" vertical="middle" />

`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 <Badge type="tip" text="v3.28.0+" vertical="middle" />

`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

```
/* 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 ---
- Files Extracted: 50
- Estimated Token Budget: ~49386 tokens
- Canonical Reference: https://codewiki.google/github.com/zh-lx/pinyin-pro
