Package Exports
- tiny-pinyin
This package does not declare an exports field, so the exports above have been automatically detected and optimized by JSPM instead. If any package subpath is missing, it is recommended to post an issue to the original package (tiny-pinyin) to support the "exports" field. If that is not possible, create a JSPM override to customize the exports field for this package.
Readme
tiny-pinyin

轻量的 汉字转拼音 JavaScript库。可以轻松获取汉字的拼音。有以下特性:
- 300行左右代码,内置一个很小的字典。
- 可以轻松处理 6763 个的常用汉字,其它汉字未测试,但应该有相当正确率,欢迎测试。
- 同时支持
node.js (4-latest)和 浏览器 (safari/chrome/firefox/android 6+/ios) 。
注意:不支持多音字;ie/edge 测试未通过。
安装和使用
使用(浏览器端使用可通过webpack等打包,或直接引入demo中已打包好的JS):
// test.js
const pinyin = require('tiny-pinyin')
if (pinyin.isSupported()) {
pinyin.convertToPinyin('我') // WO
}注意在浏览器中使用时页面的charset 必须为utf-8 ,见issue#21
一般情况下,我们的node.js只支持英文,所以,我们需要让node.js支持中文(zh-Hans-CN),即pinyin.isSupported()为true:
npm i --save full-icu通过安装full-icu,我们可以安装缺失的ICU数据文件,使node.js支持中文。通过node --icu-data-dir=node_modules/full-icu test.js即可使node.js支持全语言,正确把汉字转为拼音。
更多相关信息可以参考 full-icu-npm,或者 Node Intl。
Important: node 13+ support full icu by default
node 13 开始,node 默认开始完整的ICU支持,意味着我们不必再安装 full-icu。
详情看https://github.com/nodejs/node/blob/master/doc/changelogs/CHANGELOG_V13.md#notable-changes-16。
Demo
可点击上面的图片体验线上版本。
API
已通过 c6b3ba9@zhanba 支持 typescript typings。
1. pinyin.isSupported([forceRedetect])
forceRedetect,bool类型,是否强制重新检测。
测试环境是否支持Intl.Collator以及zh-CN。本库所有功能依赖此支持。默认只检测一次,可以置forceRedetect为true强制重新检测。
2. pinyin.parse(string)
string,待转成拼音的字符串。
返回指定字符串转成的token数组。典型的token格式如下:
{
type: Number, // 1-拉丁, 2-拼音, 3-未知
source: String, // 源字符
target: String // 目标字符
}请注意,当字符串为:
- 拉丁字母,即ascii码
0-255,不处理,原样输出,即source/target一致,type为1。 - 中文,即unicode
\u4e00-\u9FFF,转成拼音,type为2。 - 其它,即以上两者以外的字符,不处理,原样输出,
type为3。
3. pinyin.convertToPinyin(string[, separator[, lowerCase]])
string,待转成拼音的字符串。separator,拼音的分隔符,默认''。比如设置-,则我们转成WO-MEN。lowerCase,转成的拼音是否小写,默认false。仅对中文转成的拼音起效(对拉丁文字和其它文字无效)。
返回指定字符串转成的拼音字符串。
pinyin.convertToPinyin('我们和他们', '-', true) // wo-men-he-ta-men4. pinyin.patchDict(fn|[fn])
fn,function类型,接受参数为当前使用的字典对象DICT,可以修改DICT.UNIHANS/DICT.PINYINS/DICT.EXCEPTIONS来修改字典。另外,fn可以是数组,数组的每个元素为函数类型。
其中:DICT.UNIHANS/DICT.PINYINS两者相对应,记录边界汉字和其对应拼音。DICT.EXCEPTIONS是 例外 字典,为汉字-拼音的键值对,拥有更高优先级。
致谢
感谢博客利用Android源码,轻松实现汉字转拼音功能,由这篇博客才知道Android库的相关代码和汉字转拼音的原理。
非常感谢 Android Contacts Source Code。本库由它启发,可以算作Java到JavaScript的一次转译。
