Node JS Library to Convert Chinese to Pinyin
When sending parcels from UK to China, you are often required to put 'Pinyin' addresses apart from Chinese address. The Pinyin is to allow tracking put into the system. Recently, I am developing a web application that requires this feature and I am exposing this feature in a public NPM library, so this can be re-used later by other developers.
Github: https://github.com/DoctorLai/chinese_pinyin
NPM Project: https://www.npmjs.com/package/chinese_pinyin
Installation
npm install chinese_pinyin
Sample Usage
var pinyin = require('chinese_pinyin');
console.log(pinyin("你好,我是 @justyy"));
This will output:
"ni hao ,wo shi @justyy"
Dependency
None.
Test in your browser
https://npm.runkit.com/chinese_pinyin
Core Code
'use strict';
var fs = require('fs');
var contents = fs.readFileSync(__dirname + '/data/pinyin.txt', 'utf8');
var arr = contents.split(/\r?\n/);
var table = [];
arr.forEach(function(e) {
var cc = e.substr(0, 1);
var pp = e.substr(1).split(',')[0].slice(0, -1);
table[cc] = pp;
});
const pinyin = (s) => {
var ns = '';
var len = s.length;
for (var i = 0; i < len; ++ i) {
ns += table[s[i]] ? (table[s[i]] + " ") : s[i];
}
return ns.trim();
}
module.exports = pinyin;
Posted on Utopian.io - Rewarding Open Source Contributors
Thank you for the contribution. It has been approved.
You can contact us on Discord.
[utopian-moderator]
Hey @justyy I am @utopian-io. I have just upvoted you!
Achievements
Community-Driven Witness!
I am the first and only Steem Community-Driven Witness. Participate on Discord. Lets GROW TOGETHER!
Up-vote this comment to grow my power and help Open Source contributions like this one. Want to chat? Join me on Discord https://discord.gg/Pc8HG9x