pinyinUtil.js 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372
  1. /**
  2. * 汉字与拼音互转工具,根据导入的字典文件的不同支持不同
  3. * 对于多音字目前只是将所有可能的组合输出,准确识别多音字需要完善的词库,而词库文件往往比字库还要大,所以不太适合web环境。
  4. * @start 2016-09-26
  5. * @last 2016-09-29
  6. */
  7. (function(global, factory) {
  8. if (typeof module === "object" && typeof module.exports === "object") {
  9. module.exports = factory(global);
  10. } else {
  11. factory(global);
  12. }
  13. })(typeof window !== "undefined" ? window : this, function(window) {
  14. var toneMap =
  15. {
  16. "ā": "a1",
  17. "á": "a2",
  18. "ǎ": "a3",
  19. "à": "a4",
  20. "ō": "o1",
  21. "ó": "o2",
  22. "ǒ": "o3",
  23. "ò": "o4",
  24. "ē": "e1",
  25. "é": "e2",
  26. "ě": "e3",
  27. "è": "e4",
  28. "ī": "i1",
  29. "í": "i2",
  30. "ǐ": "i3",
  31. "ì": "i4",
  32. "ū": "u1",
  33. "ú": "u2",
  34. "ǔ": "u3",
  35. "ù": "u4",
  36. "ü": "v0",
  37. "ǖ": "v1",
  38. "ǘ": "v2",
  39. "ǚ": "v3",
  40. "ǜ": "v4",
  41. "ń": "n2",
  42. "ň": "n3",
  43. "": "m2"
  44. };
  45. var dict = {}; // 存储所有字典数据
  46. var pinyinUtil =
  47. {
  48. /**
  49. * 解析各种字典文件,所需的字典文件必须在本JS之前导入
  50. */
  51. parseDict: function()
  52. {
  53. // 如果导入了 pinyin_dict_firstletter.js
  54. if(window.pinyin_dict_firstletter)
  55. {
  56. dict.firstletter = pinyin_dict_firstletter;
  57. }
  58. // 如果导入了 pinyin_dict_notone.js
  59. if(window.pinyin_dict_notone)
  60. {
  61. dict.notone = {};
  62. dict.py2hz = pinyin_dict_notone; // 拼音转汉字
  63. for(var i in pinyin_dict_notone)
  64. {
  65. var temp = pinyin_dict_notone[i];
  66. for(var j=0, len=temp.length; j<len; j++)
  67. {
  68. if(!dict.notone[temp[j]]) dict.notone[temp[j]] = i; // 不考虑多音字
  69. }
  70. }
  71. }
  72. // 如果导入了 pinyin_dict_withtone.js
  73. if(window.pinyin_dict_withtone)
  74. {
  75. dict.withtone = {}; // 汉字与拼音映射,多音字用空格分开,类似这种结构:{'大': 'da tai'}
  76. var temp = pinyin_dict_withtone.split(',');
  77. for(var i=0, len = temp.length; i<len; i++)
  78. {
  79. // 这段代码耗时28毫秒左右,对性能影响不大,所以一次性处理完毕
  80. dict.withtone[String.fromCharCode(i + 19968)] = temp[i]; // 这里先不进行split(' '),因为一次性循环2万次split比较消耗性能
  81. }
  82. // 拼音 -> 汉字
  83. if(window.pinyin_dict_notone)
  84. {
  85. // 对于拼音转汉字,我们优先使用pinyin_dict_notone字典文件
  86. // 因为这个字典文件不包含生僻字,且已按照汉字使用频率排序
  87. dict.py2hz = pinyin_dict_notone; // 拼音转汉字
  88. }
  89. else
  90. {
  91. // 将字典文件解析成拼音->汉字的结构
  92. // 与先分割后逐个去掉声调相比,先一次性全部去掉声调然后再分割速度至少快了3倍,前者大约需要120毫秒,后者大约只需要30毫秒(Chrome下)
  93. var notone = pinyinUtil.removeTone(pinyin_dict_withtone).split(',');
  94. var py2hz = {}, py, hz;
  95. for(var i=0, len = notone.length; i<len; i++)
  96. {
  97. hz = String.fromCharCode(i + 19968); // 汉字
  98. py = notone[i].split(' '); // 去掉了声调的拼音数组
  99. for(var j=0; j<py.length; j++)
  100. {
  101. py2hz[py[j]] = (py2hz[py[j]] || '') + hz;
  102. }
  103. }
  104. dict.py2hz = py2hz;
  105. }
  106. }
  107. },
  108. /**
  109. * 根据汉字获取拼音,如果不是汉字直接返回原字符
  110. * @param chinese 要转换的汉字
  111. * @param splitter 分隔字符,默认用空格分隔
  112. * @param withtone 返回结果是否包含声调,默认是
  113. * @param polyphone 是否支持多音字,默认否
  114. */
  115. getPinyin: function(chinese, splitter, withtone, polyphone)
  116. {
  117. if(!chinese || /^ +$/g.test(chinese)) return '';
  118. splitter = splitter == undefined ? ' ' : splitter;
  119. withtone = withtone == undefined ? true : withtone;
  120. polyphone = polyphone == undefined ? false : polyphone;
  121. var result = [];
  122. if(dict.withtone) // 优先使用带声调的字典文件
  123. {
  124. var noChinese = '';
  125. for (var i=0, len = chinese.length; i < len; i++)
  126. {
  127. var pinyin = dict.withtone[chinese[i]];
  128. if(pinyin)
  129. {
  130. // 如果不需要多音字,默认返回第一个拼音,后面的直接忽略
  131. // 所以这对数据字典有一定要求,常见字的拼音必须放在最前面
  132. if(!polyphone) pinyin = pinyin.replace(/ .*$/g, '');
  133. if(!withtone) pinyin = this.removeTone(pinyin); // 如果不需要声调
  134. //空格,把noChinese作为一个词插入
  135. noChinese && ( result.push( noChinese), noChinese = '' );
  136. result.push( pinyin );
  137. }
  138. else if ( !chinese[i] || /^ +$/g.test(chinese[i]) ){
  139. //空格,把noChinese作为一个词插入
  140. noChinese && ( result.push( noChinese), noChinese = '' );
  141. }
  142. else{
  143. noChinese += chinese[i];
  144. }
  145. }
  146. if ( noChinese ){
  147. result.push( noChinese);
  148. noChinese = '';
  149. }
  150. }
  151. else if(dict.notone) // 使用没有声调的字典文件
  152. {
  153. if(withtone) console.warn('pinyin_dict_notone 字典文件不支持声调!');
  154. if(polyphone) console.warn('pinyin_dict_notone 字典文件不支持多音字!');
  155. var noChinese = '';
  156. for (var i=0, len = chinese.length; i < len; i++)
  157. {
  158. var temp = chinese.charAt(i),
  159. pinyin = dict.notone[temp];
  160. if ( pinyin ){ //插入拼音
  161. //空格,把noChinese作为一个词插入
  162. noChinese && ( result.push( noChinese), noChinese = '' );
  163. result.push( pinyin );
  164. }
  165. else if ( !temp || /^ +$/g.test(temp) ){
  166. //空格,插入之前的非中文字符
  167. noChinese && ( result.push( noChinese), noChinese = '' );
  168. }
  169. else {
  170. //非空格,关联到noChinese中
  171. noChinese += temp;
  172. }
  173. }
  174. if ( noChinese ){
  175. result.push( noChinese );
  176. noChinese = '';
  177. }
  178. }
  179. else
  180. {
  181. throw '抱歉,未找到合适的拼音字典文件!';
  182. }
  183. if(!polyphone) return result.join(splitter);
  184. else
  185. {
  186. if(window.pinyin_dict_polyphone) return parsePolyphone(chinese, result, splitter, withtone);
  187. else return handlePolyphone(result, ' ', splitter);
  188. }
  189. },
  190. /**
  191. * 获取汉字的拼音首字母
  192. * @param str 汉字字符串,如果遇到非汉字则原样返回
  193. * @param polyphone 是否支持多音字,默认false,如果为true,会返回所有可能的组合数组
  194. */
  195. getFirstLetter: function(str, polyphone)
  196. {
  197. polyphone = polyphone == undefined ? false : polyphone;
  198. if(!str || /^ +$/g.test(str)) return '';
  199. if(dict.firstletter) // 使用首字母字典文件
  200. {
  201. var result = [];
  202. for(var i=0; i<str.length; i++)
  203. {
  204. var unicode = str.charCodeAt(i);
  205. var ch = str.charAt(i);
  206. if(unicode >= 19968 && unicode <= 40869)
  207. {
  208. ch = dict.firstletter.all.charAt(unicode-19968);
  209. if(polyphone) ch = dict.firstletter.polyphone[unicode] || ch;
  210. }
  211. result.push(ch);
  212. }
  213. if(!polyphone) return result.join(''); // 如果不用管多音字,直接将数组拼接成字符串
  214. else return handlePolyphone(result, '', ''); // 处理多音字,此时的result类似于:['D', 'ZC', 'F']
  215. }
  216. else
  217. {
  218. var py = this.getPinyin(str, ' ', false, polyphone);
  219. py = py instanceof Array ? py : [py];
  220. var result = [];
  221. for(var i=0; i<py.length; i++)
  222. {
  223. result.push(py[i].replace(/(^| )(\w)\w*/g, function(m,$1,$2){return $2.toUpperCase();}));
  224. }
  225. if(!polyphone) return result[0];
  226. else return simpleUnique(result);
  227. }
  228. },
  229. /**
  230. * 拼音转汉字,只支持单个汉字,返回所有匹配的汉字组合
  231. * @param pinyin 单个汉字的拼音,可以包含声调
  232. */
  233. getHanzi: function(pinyin)
  234. {
  235. if(!dict.py2hz)
  236. {
  237. throw '抱歉,未找到合适的拼音字典文件!';
  238. }
  239. return dict.py2hz[this.removeTone(pinyin)] || '';
  240. },
  241. /**
  242. * 获取某个汉字的同音字,本方法暂时有问题,待完善
  243. * @param hz 单个汉字
  244. * @param sameTone 是否获取同音同声调的汉字,必须传进来的拼音带声调才支持,默认false
  245. */
  246. getSameVoiceWord: function(hz, sameTone)
  247. {
  248. sameTone = sameTone || false
  249. return this.getHanzi(this.getPinyin(hz, ' ', false))
  250. },
  251. /**
  252. * 去除拼音中的声调,比如将 xiǎo míng tóng xué 转换成 xiao ming tong xue
  253. * @param pinyin 需要转换的拼音
  254. */
  255. removeTone: function(pinyin)
  256. {
  257. return pinyin.replace(/[āáǎàōóǒòēéěèīíǐìūúǔùüǖǘǚǜńň]/g, function(m){ return toneMap[m][0]; });
  258. },
  259. /**
  260. * 将数组拼音转换成真正的带标点的拼音
  261. * @param pinyinWithoutTone 类似 xu2e这样的带数字的拼音
  262. */
  263. getTone: function(pinyinWithoutTone)
  264. {
  265. var newToneMap = {};
  266. for(var i in toneMap) newToneMap[toneMap[i]] = i;
  267. return (pinyinWithoutTone || '').replace(/[a-z]\d/g, function(m) {
  268. return newToneMap[m] || m;
  269. });
  270. }
  271. };
  272. /**
  273. * 处理多音字,将类似['D', 'ZC', 'F']转换成['DZF', 'DCF']
  274. * 或者将 ['chang zhang', 'cheng'] 转换成 ['chang cheng', 'zhang cheng']
  275. */
  276. function handlePolyphone(array, splitter, joinChar)
  277. {
  278. splitter = splitter || '';
  279. var result = [''], temp = [];
  280. for(var i=0; i<array.length; i++)
  281. {
  282. temp = [];
  283. var t = array[i].split(splitter);
  284. for(var j=0; j<t.length; j++)
  285. {
  286. for(var k=0; k<result.length; k++)
  287. temp.push(result[k] + (result[k]?joinChar:'') + t[j]);
  288. }
  289. result = temp;
  290. }
  291. return simpleUnique(result);
  292. }
  293. /**
  294. * 根据词库找出多音字正确的读音
  295. * 这里只是非常简单的实现,效率和效果都有一些问题
  296. * 推荐使用第三方分词工具先对句子进行分词,然后再匹配多音字
  297. * @param chinese 需要转换的汉字
  298. * @param result 初步匹配出来的包含多个发音的拼音结果
  299. * @param splitter 返回结果拼接字符
  300. */
  301. function parsePolyphone(chinese, result, splitter, withtone)
  302. {
  303. var poly = window.pinyin_dict_polyphone;
  304. var max = 7; // 最多只考虑7个汉字的多音字词,虽然词库里面有10个字的,但是数量非常少,为了整体效率暂时忽略之
  305. var temp = poly[chinese];
  306. if(temp) // 如果直接找到了结果
  307. {
  308. temp = temp.split(' ');
  309. for(var i=0; i<temp.length; i++)
  310. {
  311. result[i] = temp[i] || result[i];
  312. if(!withtone) result[i] = pinyinUtil.removeTone(result[i]);
  313. }
  314. return result.join(splitter);
  315. }
  316. for(var i=0; i<chinese.length; i++)
  317. {
  318. temp = '';
  319. for(var j=0; j<max && (i+j)<chinese.length; j++)
  320. {
  321. if(!/^[\u2E80-\u9FFF]+$/.test(chinese[i+j])) break; // 如果碰到非汉字直接停止本次查找
  322. temp += chinese[i+j];
  323. var res = poly[temp];
  324. if(res) // 如果找到了多音字词语
  325. {
  326. res = res.split(' ');
  327. for(var k=0; k<=j; k++)
  328. {
  329. if(res[k]) result[i+k] = withtone ? res[k] : pinyinUtil.removeTone(res[k]);
  330. }
  331. break;
  332. }
  333. }
  334. }
  335. // 最后这一步是为了防止出现词库里面也没有包含的多音字词语
  336. for(var i=0; i<result.length; i++)
  337. {
  338. result[i] = result[i].replace(/ .*$/g, '');
  339. }
  340. return result.join(splitter);
  341. }
  342. // 简单数组去重
  343. function simpleUnique(array)
  344. {
  345. var result = [];
  346. var hash = {};
  347. for(var i=0; i<array.length; i++)
  348. {
  349. var key = (typeof array[i]) + array[i];
  350. if(!hash[key])
  351. {
  352. result.push(array[i]);
  353. hash[key] = true;
  354. }
  355. }
  356. return result;
  357. }
  358. pinyinUtil.parseDict();
  359. pinyinUtil.dict = dict;
  360. window.pinyinUtil = pinyinUtil;
  361. });