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

编辑推荐精选

讯飞智文

讯飞智文

一键生成PPT和Word,让学习生活更轻松

讯飞智文是一个利用 AI 技术的项目,能够帮助用户生成 PPT 以及各类文档。无论是商业领域的市场分析报告、年度目标制定,还是学生群体的职业生涯规划、实习避坑指南,亦或是活动策划、旅游攻略等内容,它都能提供支持,帮助用户精准表达,轻松呈现各种信息。

AI办公办公工具AI工具讯飞智文AI在线生成PPTAI撰写助手多语种文档生成AI自动配图热门
��讯飞星火

讯飞星火

深度推理能力全新升级,全面对标OpenAI o1

科大讯飞的星火大模型,支持语言理解、知识问答和文本创作等多功能,适用于多种文件和业务场景,提升办公和日常生活的效率。讯飞星火是一个提供丰富智能服务的平台,涵盖科技资讯、图像创作、写作辅助、编程解答、科研文献解读等功能,能为不同需求的用户提供便捷高效的帮助,助力用户轻松获取信息、解决问题,满足多样化使用场景。

热门AI开发模型训练AI工具讯飞星火大模型智能问答内容创作多语种支持智慧生活
Spark-TTS

Spark-TTS

一种基于大语言模型的高效单流解耦语音令牌文本到语音合成模型

Spark-TTS 是一个基于 PyTorch 的开源文本到语音合成项目,由多个知名机构联合参与。该项目提供了高效的 LLM(大语言模型)驱动的语音合成方案,支持语音克隆和语音创建功能,可通过命令行界面(CLI)和 Web UI 两种方式使用。用户可以根据需求调整语音的性别、音高、速度等参数,生成高质量的语音。该项目适用于多种场景,如有声读物制作、智能语音助手开发等。

Trae

Trae

字节跳动发布的AI编程神器IDE

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

AI工具TraeAI IDE协作生产力转型热门
咔片PPT

咔片PPT

AI助力,做PPT更简单!

咔片是一款轻量化在线演示设计工具,借助 AI 技术,实现从内容生成到智能设计的一站式 PPT 制作服务。支持多种文档格式导入生成 PPT,提供海量模板、智能美化、素材替换等功能,适用于销售、教师、学生等各类人群,能高效制作出高品质 PPT,满足不同场景演示需求。

讯飞绘文

讯飞绘文

选题、配图、成文,一站式创作,让内容运营更高效

讯飞绘文,一个AI集成平台,支持写作、选题、配图、排版和发布。高效生成适用于各类媒体的定制内容,加速品牌传播,提升内容营销效果。

热门AI辅助写作AI工具讯飞绘文内容运营AI创作个性化文章多平台分发AI助手
材料星

材料星

专业的AI公文写作平台,公文写作神器

AI 材料星,专业的 AI 公文写作辅助平台,为体制内工作人员提供高效的公文写作解决方案。拥有海量公文文库、9 大核心 AI 功能,支持 30 + 文稿类型生成,助力快速完成领导讲话、工作总结、述职报告等材料,提升办公效率,是体制打工人的得力写作神器。

openai-agents-python

openai-agents-python

OpenAI Agents SDK,助力开发者便捷使用 OpenAI 相关功能。

openai-agents-python 是 OpenAI 推出的一款强大 Python SDK,它为开发者提供了与 OpenAI 模型交互的高效工具,支持工具调用、结果处理、追踪等功能,涵盖多种应用场景,如研究助手、财务研究等,能显著提升开发效率,让开发者更轻松地利用 OpenAI 的技术优势。

Hunyuan3D-2

Hunyuan3D-2

高分辨率纹理 3D 资产生成

Hunyuan3D-2 是腾讯开发的用于 3D 资产生成的强大工具,支持从文本描述、单张图片或多视角图片生成 3D 模型,具备快速形状生成能力,可生成带纹理的高质量 3D 模型,适用于多个领域,为 3D 创作提供了高效解决方案。

3FS

3FS

一个具备存储、管理和客户端操作等多种功能的分布式文件系统相关项目。

3FS 是一个功能强大的分布式文件系统项目,涵盖了存储引擎、元数据管理、客户端工具等多个模块。它支持多种文件操作,如创建文件和目录、设置布局等,同时具备高效的事件循环、节点选择和协程池管理等特性。适用于需要大规模数据存储和管理的场景,能够提高系统的性能和可靠性,是分布式存储领域的优质解决方案。

下拉加载更多