pīnyīn (v3)
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
类型
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".
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.
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版。 |
繁体中文 | 没有繁体中文支持。 | 有简单的繁简汉字转换。 |
由于这些区别,测试不同运行环境的用例也不尽相同。
捐赠
如果这个模块对您有帮助,请给这个仓库点个星。
您也可以选择使用支付宝或微信给我捐赠: