New Case Study:See how Anthropic automated 95% of dependency reviews with Socket.Learn More
Socket
Sign inDemoInstall
Socket

tiny-pinyin

Package Overview
Dependencies
Maintainers
1
Versions
7
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

tiny-pinyin

convert hanzi to pinyin

  • 1.0.0
  • Source
  • npm
  • Socket score

Version published
Weekly downloads
9.3K
increased by1.53%
Maintainers
1
Weekly downloads
 
Created
Source

tiny-pinyin Build Status

English Doc

轻量的 汉字转拼音 JavaScript库。可以轻松获取汉字的拼音。有以下特性:

  1. 300行左右代码,内置一个很小的字典。
  2. 可以轻松处理 6763 个的常用汉字,其它汉字未测试,但应该有相当正确率,欢迎测试。
  3. 同时支持 node.js和浏览器

Demo

可点击上面的图片体验线上版本

安装和使用

安装:$ npm i --save tiny-pinyin

使用:

// test.js
const pinyin = require('tiny-pinyin')

if (pinyin.isSupported()) {
  pinyin.convertToPinyin('我') // WO
}

一般情况下,我们的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

API

1. pinyin.isSupported([forceRedetect])

  • forceRedetectbool类型,是否强制重新检测。

测试环境是否支持Intl.Collator以及zh-CN。本库所有功能依赖此支持。默认只检测一次,可以置forceRedetecttrue强制重新检测。

2. pinyin.parse(string)

  • string,待转成拼音的字符串。

返回指定字符串转成的token数组。典型的token格式如下:

{
  type: Number, // 1-拉丁, 2-拼音, 3-未知
  source: String, // 源字符
  target: String // 目标字符
}

请注意,当字符串为

  1. 拉丁字母,即ascii码0-255,不处理,原样输出,即source/target一致,type1
  2. 中文,即unicode \u4e00-\u9FFF ,转成拼音,type2
  3. 其它,即以上两者以外的字符,不处理,原样输出,type3

3. pinyin.convertToPinyin(string, separator, lowerCase)

  • string,待转成拼音的字符串。
  • separator,拼音的分隔符,默认''。比如设置-,则我们转成WO-MEN
  • lowerCase,转成的拼音是否小写,默认false。仅对中文转成的拼音起效(对拉丁文字和其它文字无效)。

返回指定字符串转成的拼音字符串。

pinyin.convertToPinyin('我们和他们', '-', true) // wo-men-he-ta-men

致谢

感谢博客利用Android源码,轻松实现汉字转拼音功能,由这篇博客才知道Android库的相关代码和汉字转拼音的原理。

非常感谢 Android Contacts Source Code。本库由它启发,可以算作Java到JavaScript的一次转译。

Keywords

FAQs

Package last updated on 12 May 2017

Did you know?

Socket

Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.

Install

Related posts

SocketSocket SOC 2 Logo

Product

  • Package Alerts
  • Integrations
  • Docs
  • Pricing
  • FAQ
  • Roadmap
  • Changelog

Packages

npm

Stay in touch

Get open source security insights delivered straight into your inbox.


  • Terms
  • Privacy
  • Security

Made with ⚡️ by Socket Inc