pīnyīn,汉字拼音转换工具。
将中文字符转换为拼音。可用于汉字注音、排序、检索。
注:此版本同时支持在 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
传入给 pinyin 方法的第二个参数的选项类型。
export interface IPinyinOptions { style?: IPinyinStyle; // 拼音输出形式 mode?: IPinyinMode, // 拼音模式 // 指定分词库。 // 为了兼容老版本,可以使用 boolean 类型指定是否开启分词,默认开启。 segment?: IPinyinSegment | boolean; // 是否返回多音字 heteronym?: boolean; // 是否分组词组拼音 group?: boolean; compact?: boolean; }
输出拼音格式。可以直接使用以下字符串或数字,也兼容 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; // 兼容老版本
拼音模式,默认普通模式,可以指定人名模式。
// - NORMAL: 普通模式 // - SURNAME: 姓氏模式,优先使用姓氏的拼音。 export type IPinyinMode = "normal" | "surname" | "NORMAL" | "SURNAME";
分词方式。
false,true 开启,Web 和 Node 版中均使用 "Intl.Segmenter" 分词。export type IPinyinSegment = "Intl.Segmenter" | "nodejieba" | "segmentit" | "@node-rs/jieba";
<Array> pinyin(words: string[, options: IPinyinOptions])将传入的中文字符串 (words) 转换成拼音符号串。
options 是可选的,可以设定拼音风格,或打开多音字选项。
返回二维数组,第一维每个数组项位置对应每个中文字符串位置。 第二 维是各个汉字的读音列表,多音字会有多个拼音项。
Number compare(a, b)按拼音排序的默认算法。
string[][] compact(pinyinResult array[][])将拼音多音字以各种可能的组合排列变换成紧凑形式。参考 options.compact
<Boolean|IPinyinSegment> options.segmentWhether 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.
segment = true, Intl.Segmenter is used for segmentation by default.<Boolean> options.heteronymWhether 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.groupGroup pinyin by phrases, for example:
我喜欢你
wǒ xǐhuān nǐ
<IPinyinStyle> options.styleSpecify 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, normalNormal style, without tones.
Example: pin yin
TONE, toneTone style, with tone marks on the first vowel of each syllable.
Note: This is the default style.
Example: pīn yīn
TONE2, tone2Tone style 2, with tone numbers [0-4] after each pinyin syllable.
Example: pin1 yin1
TO3NE, to3neTone style 3, with tone numbers [0-4] after the phonetic characters.
Example: pi1n yi1n
INITIALS, initialsInitial 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_letterFirst letter style, only returns the first letter of each pinyin syllable.
Example: p y
PASSPORT, passportPassport 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".
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.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.
npm test
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
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);
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" />

全球首个AI音乐社区
音述AI是全球首个AI音乐社区, 致力让每个人都能用音乐表达自我。音述AI提供零门槛AI创作工具,独创GETI法则帮助用户精准定义音乐风格,AI润色功能支持自动优化作品质感。音述AI支持交流讨论、二次创作与价值变现。针对中文用户的语言习惯与文化背景进行专门优化,支持国风融合、C-pop等本土音乐标签,让技术更好地承载人文表达。


一站式搞定所有学习需求
不再被海量信息淹没,开始真正理解知识。Lynote 可摘要 YouTube 视频、PDF、文章等内容。即时创建笔记,检测 AI 内容并下载资料,将您的学习效率提升 10 倍。


为AI短剧协作而生
专为AI短剧协作而生的AniShort正式发布,深度重构AI短剧全流程生产模式,整合创意策划、制作执行、实时协作、在线审片、资产复用等全链路功能,独创无限画布、双轨并行工业化工作流与Ani智能体助手,集成多款主流AI大模型,破解素材零散、版本混乱、沟通低效等行业痛点,助力3人团队效率提升800%,打造标准化、可追溯的AI短剧量产体系,是AI短剧团队协同创作、提升制作效率的核心工具。


能听懂你表达的视频模型
Seedance two是基于seedance2.0的中国大模型,支持图像、视频、音频、文本四种模态输入,表达方式更丰富,生成也更可控。


国内直接访问,限时3折
输入简单文字,生成想要的图片,纳米香蕉中文站基于 Google 模型的 AI 图片生成网站,支持文字生图、图生图。官网价格限时3折活动


职场AI,就用扣子
AI办公助手,复杂任务高效处理。办公效率低?扣子空间AI助手支持播客生成、PPT制作、网页开发及报告写作,覆盖科研、商业、舆情等领域的专家Agent 7x24小时响应,生活工作无缝切换,提升50%效率!


多风格AI绘画神器
堆友平台由阿里巴巴设计团队创建,作为一款AI驱动的设计工具,专为设计师提供一站式增长服务。功能覆盖海量3D素材、AI绘画、实时渲染以及专业抠图,显著提升设计品质和效率。平台不仅提供工具,还是一个促进创意交流和个人发展的空间,界面友好,适合所有级别的设计师和创意工作者。


零代码AI应用开发平台
零代码AI应用开发平台,用户只需一句话简单描述需求,AI能自动生成小程序、APP或H5网页应用,无需编写代码。


免费创建高清无水印Sora视频
Vora是一个免费创建高清无水印Sora视频的AI工具


最适合小白的AI自动化工作流平台
无需编码,轻松生成可复用、可变现的AI自动化工作流
最新AI工具、AI资讯
独家AI资源、AI项目落地

微信扫一扫关注公众号