pinyin

pinyin

多功能汉字拼音转换工具 支持多音字识别和智能分词

pinyin是一个开源的汉字拼音转换工具,支持多音字识别和智能分词。它提供多种拼音输出风格,可用于汉字注音、排序和检索。该工具适用于Node.js和Web环境,具有可定制性强的特点。用户可以选择不同的分词方式和拼音模式,以适应各种应用场景。pinyin还包含命令行接口,方便快速使用。

汉字拼音拼音转换多音字分词Node.jsGithub开源项目

pīnyīn (v3)

pīnyīn,汉字拼音转换工具。


NPM 版本 构建状态 覆盖率状态 语言等级: JavaScript NPM 下载量

网站: 简体中文 | English | 한국어

README: 简体中文 | English | 한국어

将中文字符转换为拼音。可用于汉字注音、排序、检索。

注:此版本同时支持在 Node 和 Web 浏览器环境运行,

Python 版请关注 mozillazg/python-pinyin


特性

  • 根据词组智能匹配最正确的拼音。
  • 支持多音字。
  • 简单的繁体支持。
  • 支持多种不同拼音风格。

安装

通过 npm:

npm install pinyin --save

用法

开发者:

import pinyin from "pinyin"; console.log(pinyin("中心")); // [ [ 'zhōng' ], [ 'xīn' ] ] console.log(pinyin("中心", { heteronym: true, // 启用多音字模式 })); // [ [ 'zhōng', 'zhòng' ], [ 'xīn' ] ] console.log(pinyin("中心", { heteronym: true, // 启用多音字模式 segment: true, // 启用分词,以解决多音字问题。默认不开启,使用 true 开启使用 Intl.Segmenter 分词库。 })); // [ [ 'zhōng' ], [ 'xīn' ] ] console.log(pinyin("中心", { segment: "@node-rs/jieba", // 指定分词库,可以是 "Intl.Segmenter", "nodejieba"、"segmentit"、"@node-rs/jieba"。 })); // [ [ 'zhōng' ], [ 'xīn' ] ] console.log(pinyin("我喜欢你", { segment: "segmentit", // 启用分词 group: true, // 启用词组 })); // [ [ 'wǒ' ], [ 'xǐhuān' ], [ 'nǐ' ] ] console.log(pinyin("中心", { style: "initials", // 设置拼音风格。 heteronym: true, // 即使有多音字,因为拼音风格选择,重复的也会合并。 })); // [ [ 'zh' ], [ 'x' ] ] console.log(pinyin("华夫人", { mode: "surname", // 姓名模式。 })); // [ ['huà'], ['fū'], ['rén'] ]

命令行:

$ pinyin 中心 zhōng xīn $ pinyin -h

类型

IPinyinOptions

传入给 pinyin 方法的第二个参数的选项类型。

export interface IPinyinOptions { style?: IPinyinStyle; // 拼音输出形式 mode?: IPinyinMode, // 拼音模式 // 指定分词库。 // 为了兼容老版本,可以使用 boolean 类型指定是否开启分词,默认开启。 segment?: IPinyinSegment | boolean; // 是否返回多音字 heteronym?: boolean; // 是否分组词组拼音 group?: boolean; compact?: boolean; }

IPinyinStyle

输出拼音格式。可以直接使用以下字符串或数字,也兼容 v2 版本中 pinyin.STYLE_TONE 这样的形式。

export type IPinyinStyle = "normal" | "tone" | "tone2" | "to3ne" | "initials" | "first_letter" | "passport" | // 推荐使用小写,和输出的拼音一致 "NORMAL" | "TONE" | "TONE2" | "TO3NE" | "INITIALS" | "FIRST_LETTER" | "PASSPORT" | // 方便老版本迁移 0 | 1 | 2 | 5 | 3 | 4; // 兼容老版本

IPinyinMode

拼音模式,默认普通模式,可以指定人名模式。

// - NORMAL: 普通模式 // - SURNAME: 姓氏模式,优先使用姓氏的拼音。 export type IPinyinMode = "normal" | "surname" | "NORMAL" | "SURNAME";

IPinyinSegment

分词方式。

  • 默认关闭 false
  • 也可以设置为 true 开启,Web 和 Node 版中均使用 "Intl.Segmenter" 分词。
  • 也可以声明以下字符串来指定分词算法。但目前 Web 版只支持 "Intl.Segmenter" 和 "segmentit" 分词。
export type IPinyinSegment = "Intl.Segmenter" | "nodejieba" | "segmentit" | "@node-rs/jieba";

API

方法 <Array> pinyin(words: string[, options: IPinyinOptions])

将传入的中文字符串 (words) 转换成拼音符号串。

options 是可选的,可以设定拼音风格,或打开多音字选项。

返回二维数组,第一维每个数组项位置对应每个中文字符串位置。 第二维是各个汉字的读音列表,多音字会有多个拼音项。

方法 Number compare(a, b)

按拼音排序的默认算法。

方法 string[][] compact(pinyinResult array[][])

将拼音多音字以各种可能的组合排列变换成紧凑形式。参考 options.compact

参数

<Boolean|IPinyinSegment> options.segment

Whether to enable word segmentation mode. Chinese word segmentation helps greatly reduce issues with multi-pronunciation characters. However, performance will significantly decrease and more memory will be used.

  • Word segmentation is disabled by default.
  • If segment = true, Intl.Segmenter is used for segmentation by default.
  • You can specify "Intl.Segmenter", "nodejieba", "segmentit", or "@node-rs/jieba" for segmentation.

<Boolean> options.heteronym

Whether to enable multi-pronunciation mode, disabled by default.

When multi-pronunciation mode is off, it returns the first matching pinyin for each Chinese character.

When multi-pronunciation mode is on, it returns all possible pinyin lists for multi-pronunciation characters.

<Boolean> options.group

Group pinyin by phrases, for example:

我喜欢你
wǒ xǐhuān nǐ

<IPinyinStyle> options.style

Specify the pinyin style. You can use the following specific strings or values:

IPinyinStyle = "normal" | "tone" | "tone2" | "to3ne" | "initials" | "first_letter" | "passport" | // Lowercase recommended, consistent with output pinyin "NORMAL" | "TONE" | "TONE2" | "TO3NE" | "INITIALS" | "FIRST_LETTER" | "PASSPORT" | // For easy migration from older versions 0 | 1 | 2 | 5 | 3 | 4; // Compatible with older versions

NORMAL, normal

Normal style, without tones.

Example: pin yin

TONE, tone

Tone style, with tone marks on the first vowel of each syllable.

Note: This is the default style.

Example: pīn yīn

TONE2, tone2

Tone style 2, with tone numbers [0-4] after each pinyin syllable.

Example: pin1 yin1

TO3NE, to3ne

Tone style 3, with tone numbers [0-4] after the phonetic characters.

Example: pi1n yi1n

INITIALS, initials

Initial consonant style, only returns the initial consonant part of each pinyin. For characters without initial consonants, returns an empty string.

Example: Pinyin for 中国 is zh g

Note: Initial consonant style distinguishes between zh and z, ch and c, sh and s.

Note: Some Chinese characters don't have initial consonants, such as , 饿, etc. Also, y, w, yu are not initial consonants. The initial consonant style for these characters will return "". Please carefully consider if your needs are better met by the first letter style. For details, please refer to Why are there no initials y, w, yu

FIRST_LETTER, first_letter

First letter style, only returns the first letter of each pinyin syllable.

Example: p y

PASSPORT, passport

Passport style. Converts to uppercase, and ü is output as YU.

The National Immigration Administration portal website released the "Announcement on the Printing Rules of the Letter 'ü' in Pinyin Names of Mainland Residents in Exit and Entry Documents" on September 29, 2021. According to the "Chinese Pinyin Spelling Rules for Chinese Names" and "International Common Standards for Machine-Readable Travel Documents", when mainland residents apply for exit and entry documents, the letter "ü" in Lü (吕 and similar characters) and Nü (女 and similar characters) in the pinyin names printed on exit and entry documents should be converted to "YU", and the letter "ü" in LüE (略 and similar characters) and NüE (虐 and similar characters) should be converted to "U".

<string> options.mode

Pinyin mode, default is "NORMAL" (normal mode). If you are specifically in a name scenario, you can use "SURNAME" for more accurate pronunciation of surnames.

  • NORMAL: Normal mode, automatically recognizes pronunciation.
  • SURNAME: Name mode, for specific name scenarios, can more accurately recognize the pronunciation of surnames.

<boolean> options.compact

Whether to return compact mode, default is false, returns in standard format. If set to true, it will return all possible combinations of multi-pronunciation characters arranged. For example:

pinyin("你好吗", { compact:false });
> [[nǐ], [hǎo,hào], [ma,má,mǎ]]

pinyin("你好吗", { compact:true });
> [
>   [nǐ,hǎo,ma], [nǐ,hǎo,má], [nǐ,hǎo,mǎ],
>   [nǐ,hào,ma], [nǐ,hào,má], [nǐ,hào,mǎ],
> ]

You can also use the compact() function to process the results returned by pinyin(han, {compact:false}) when necessary.

Test

npm test

Q&A

About how to use the Web version

First, I recommend that everyone should prioritize converting pinyin on the server-side once and persisting the results, to avoid performance and experience losses from converting on the client-side each time.

If you insist on using it on the client-side, you can consider using Webpack + Babel to convert it into executable code for low-end browsers.

If you really don't want to bother, you can try https://github.com/hotoo/pinyin/tree/gh-pages/dist

Why are there no initials y, w, yu?

In the initial consonant style (INITIALS), characters like "雨", "我", "圆" return an empty string because according to the "Hanyu Pinyin Scheme", y, w, ü (yu) are not initial consonants. They are only added before certain vowels when there is no initial consonant, and ü also has its specific rules. 如果你觉得这给你带来了麻烦,那么也请小心一些没有声母的汉字(如"啊"、"饿"、"按"、"昂"等)。 这时你可能需要的是首字母风格(FIRST_LETTER)。

如何实现按拼音排序?

pinyin 模块提供了默认的排序方案:

const pinyin = require('pinyin'); const data = '我要排序'.split(''); const sortedData = data.sort(pinyin.compare);

如果默认的比较方法不能满足你的需求,你可以自定义 pinyinCompare 方法:

const pinyin = require('pinyin'); const data = '我要排序'.split(''); // 建议将汉字的拼音持久化存储起来。 const pinyinData = data.map(han => ({ han: han, pinyin: pinyin(han)[0][0], // 可以自行选择不同的生成拼音方案和风格。 })); const sortedData = pinyinData.sort((a, b) => { return a.pinyin.localeCompare(b.pinyin); }).map(d => d.han);

Node版和Web版有什么异同?

pinyin 目前可以同时运行在Node服务器端和Web浏览器端。 API和使用方式完全一致。

但Web版相比Node版稍简单,拼音库只包含常用字部分,没有使用分词算法, 并且考虑到网络传输对词库进行了压缩处理。

由于分词和繁体中文的特性,部分情况下的结果也不尽相同。

特性Web版Node版
拼音库常用字库。压缩、合并完整字库。不压缩、合并
分词没有分词使用分词算法,多音字拼音更准确。
拼音频度排序有根据拼音使用频度优先级排序。同Web版。
繁体中文没有繁体中文支持。有简单的繁简汉字转换。

由于这些区别,测试不同运行环境的用例也不尽相同。

捐赠

如果这个模块对您有帮助,请给这个仓库点个星。

您也可以选择使用支付宝或微信给我捐赠:

<img src="https://yellow-cdn.veclightyear.com/0a4dffa0/c9ff6dee-210b-4f56-9e31-3f6a0a71e738.png" alt="支付宝:hotoo.cn@gmail.com,微信:hotoome" width="400" />

许可证

MIT

编辑推荐精选

Refly.AI

Refly.AI

最适合小白的AI自动化工作流平台

无需编码,轻松生成可复用、可变现的AI自动化工作流

酷表ChatExcel

酷表ChatExcel

大模型驱动的Excel数据处理工具

基于大模型交互的表格处理系统,允许用户通过对话方式完成数据整理和可视化分析。系统采用机器学习算法解析用户指令,自动执行排序、公式计算和数据透视等操作,支持多种文件格式导入导出。数据处理响应速度保持在0.8秒以内,支持超过100万行数据的即时分析。

AI工具酷表ChatExcelAI智能客服AI营销产品使用教程
TRAE编程

TRAE编程

AI辅助编程,代码自动修复

Trae是一种自适应的集成开发环境(IDE),通过自动化和多元协作改变开发流程。利用Trae,团队能够更快速、精确地编写和部署代码,从而提高编程效率和项目交付速度。Trae具备上下文感知和代码自动完成功能,是提升开发效率的理想工具。

AI工具TraeAI IDE协作生产力转型热门
AIWritePaper论文写作

AIWritePaper论文写作

AI论文写作指导平台

AIWritePaper论文写作是一站式AI论文写作辅助工具,简化了选题、文献检索至论文撰写的整个过程。通过简单设定,平台可快速生成高质量论文大纲和全文,配合图表、参考文献等一应俱全,同时提供开题报告和答辩PPT等增值服务,保障数据安全,有效提升写作效率和论文质量。

AI辅助写作AI工具AI论文工具论文写作智能生成大纲数据安全AI助手热门
博思AIPPT

博思AIPPT

AI一键生成PPT,就用博思AIPPT!

博思AIPPT,新一代的AI生成PPT平台,支持智能生成PPT、AI美化PPT、文本&链接生成PPT、导入Word/PDF/Markdown文档生成PPT等,内置海量精美PPT模板,涵盖商务、教育、科技等不同风格,同时针对每个页面提供多种版式,一键自适应切换,完美适配各种办公场景。

AI办公办公工具AI工具博思AIPPTAI生成PPT智能排版海量精品模板AI创作热门
潮际好麦

潮际好麦

AI赋能电商视觉革命,一站式智能商拍平台

潮际好麦深耕服装行业,是国内AI试衣效果最好的软件。使用先进AIGC能力为电商卖家批量提供优质的、低成本的商拍图。合作品牌有Shein、Lazada、安踏、百丽等65个国内外头部品牌,以及国内10万+淘宝、天猫、京东等主流平台的品牌商家,为卖家节省将近85%的出图成本,提升约3倍出图效率,让品牌能够快速上架。

iTerms

iTerms

企业专属的AI法律顾问

iTerms是法大大集团旗下法律子品牌,基于最先进的大语言模型(LLM)、专业的法律知识库和强大的智能体架构,帮助企业扫清合规障碍,筑牢风控防线,成为您企业专属的AI法律顾问。

SimilarWeb流量提升

SimilarWeb流量提升

稳定高效的流量提升解决方案,助力品牌曝光

稳定高效的流量提升解决方案,助力品牌曝光

Sora2视频免费生成

Sora2视频免费生成

最新版Sora2模型免费使用,一键生成无水印视频

最新版Sora2模型免费使用,一键生成无水印视频

Transly

Transly

实时语音翻译/同声传译工具

Transly是一个多场景的AI大语言模型驱动的同声传译、专业翻译助手,它拥有超精准的音频识别翻译能力,几乎零延迟的使用体验和支持多国语言可以让你带它走遍全球,无论你是留学生、商务人士、韩剧美剧爱好者,还是出国游玩、多国会议、跨国追星等等,都可以满足你所有需要同传的场景需求,线上线下通用,扫除语言障碍,让全世界的语言交流不再有国界。

下拉加载更多