在很多时候我们遇到了各种各样的问题,就是在类似于suggest当中需要输入汉字转为拼音或者跟据拼音来产生热门的关键词。

热门关键词在这里我们暂时不做讨论。我们来说一下拼音处理的手法。在拼音处理的过程中有一个方案必须要做到的就是有一个拼音库。在这儿我会把拼音库给大家,让大家进行下载。

此拼音处理类存在的问题是效率过低,我们在处理的时候建议写成PHP扩展的模式来进行处理。在下一期中我们将使用PHP扩展的模式来进行处理和讲解。

拼音库的下载地址:http://www.mdbg.net/chindict/chindict.php?page=cedict

下面是使用演示:

echo Pinyin::trans(‘带着希望去旅行,比到达终点更美好’), “\n”;

//output: “dài zhe xī wàng qù lǔ xíng bǐ dào dá zhōng diǎn gèng měi hǎo”*

下面是实现的代码:

class Pinyin

{

/**

* dictionary path

*

* @var string

*/

protected $dictionary;

/**

* settings

*

* @var array

*/

protected static $setting = array(

‘delimiter’ => ‘ ‘,

‘accent’ => true,

);

/**

* instance

*

* @var Pinyin

*/

protected static $instance;

/**

* constructor

*

* set dictionary path.

*/

public function __construct()

{

ini_set(‘memory_limit’, ‘160M’);

$this->dictionary = __DIR__ . ‘/cedict/cedict_ts.u8′;

}

/**

* set the dictionary.

*

* @param array $setting settings.

*/

public static function set(array $setting = array())

{

self::$setting = array_merge(self::$setting, $setting);

}

/**

* get Pinyin instance

*

* @return Pinyin

*/

public static function getInstance()

{

if (is_null(self::$instance)) {

self::$instance = new self;

}

return self::$instance;

}

/**

* chinese to pinyin

*

* @param string $string source string.

* @param array $setting settings.

*

* @return string

*/

public static function trans($string, array $setting = array())

{

$instance = self::getInstance();

// merge setting

empty($setting) || self::set($setting);

$dictionary = $instance->loadDictionary();

// do replace

foreach ($dictionary as $line) {

$string = str_replace($line['simplified'], “{$line['pinyin_marks']} “, $string);

if (!$instance->containsChinese($string)) {

break;

}

}

// add accents

if(self::$setting['accent']) {

$string = $instance->pinyin_addaccents(strtolower($string));

} else {

$string = $instance->removeTone(strtolower($string));

}

// clean the string

$string = $instance->removeUnwantedCharacters($string);

// add delimiter

$string = $instance->addDelimiter($string);

return $instance->escape($string);

}

/**

* load dictionary content

*

* @return array

*/

protected function loadDictionary()

{

$cacheFilename = $this->getCacheFilename($this->dictionary);

// load from cache

if (file_exists($cacheFilename)) {

return $this->loadFromCache($cacheFilename);

}

// parse and cache

$parsedDictionary = $this->parseDictionary($this->dictionary);

$this->cache($cacheFilename, $parsedDictionary);

return $parsedDictionary;

}

/**

* get the filename of cache file.

*

* @param string $dictionary dictionary path.

*

* @return string

*/

protected function getCacheFilename($dictionary)

{

is_dir(__DIR__ .’/cache/’) || mkdir(__DIR__ .’/cache/’, 0755, true);

return __DIR__ .’/cache/’ . md5($dictionary);

}

/**

* parse the dict to php array

*

* @param string $dictionary path of dictionary file.

*

* @return array

*/

protected function parseDictionary($dictionary)

{

//ini_set(‘memory_limit’, ‘180M’);

$dictionary = file($dictionary);

$regex = “#(.*?) (.*?) \[(.*?)\] \/(.*)\/#”;

$content = array();

foreach ($dictionary as $entry) {

if (0 === stripos($entry, ‘#’)) {

continue;

}

preg_match($regex, $entry, $matches);

$content[] = array(

//’traditional’ => $matches[1],

‘simplified’ => $matches[2],

//’pinyin_numbers’ => $matches[3],

‘pinyin_marks’ => $matches[3],

//’translation’ => $this->escape($matches[4]),

);

}

// sort by simplified string length.

usort($content, function($a, $b){

if (mb_strlen($a['simplified']) == mb_strlen($b['simplified'])) {

return 0;

}

return mb_strlen($a['simplified']) < mb_strlen($b['simplified']) ? 1 : -1;

});

return $content;

}

/**

* load dictionary from cached file

*

* @param string $dictionary cached file name

*

* @return array

*/

protected function loadFromCache($dictionary)

{

return include $dictionary;

}

/**

* write array to file

*

* @param string $filename filename.

* @param array $array parsed dictionary.

*

* @return void

*/

protected function cache($filename, $array)

{

file_put_contents($filename, “ ‘u’,

‘/\d/’ => ”,

);

return preg_replace(array_keys($replacement), $replacement, $string);

}

/**

* Credits for these 2 functions go to Bouke Versteegh, who shared these

* at http://stackoverflow.com/questions/1598856/convert-numbered-to-accentuated-pinyin

*

* @param string $string The pinyin string with tone numbers, i.e. “ni3 hao3″

*

* @return string The formatted string with tone marks, i.e.

*/

protected function pinyin_addaccents($string)

{

# Find words with a number behind them, and replace with callback fn.

return str_replace(‘u:’, ‘ü’, preg_replace_callback(

‘~([a-zA-ZüÜ]+\:?)(\d)~’,

array($this, ‘pinyin_addaccents_cb’),

$string));

}

# Helper callback

protected function pinyin_addaccents_cb($match)

{

static $accentmap = null;

if ($accentmap === null) {

# Where to place the accent marks

$stars =

‘a* e* i* o* u* ü* ‘ .

‘A* E* I* O* U* Ü* ‘ .

‘a*i a*o e*i ia* ia*o ie* io* iu* ‘ .

‘A*I A*O E*I IA* IA*O IE* IO* IU* ‘ .

‘o*u ua* ua*i ue* ui* uo* üe* ‘ .

‘O*U UA* UA*I UE* UI* UO* ÜE*';

$nostars =

‘a e i o u ü ‘ .

‘A E I O U Ü ‘ .

‘ai ao ei ia iao ie io iu ‘ .

‘AI AO EI IA IAO IE IO IU ‘ .

‘ou ua uai ue ui uo üe ‘ .

‘OU UA UAI UE UI UO ÜE';

# Build an array like array(‘a’ => ‘a*’) and store statically

$accentmap = array_combine(explode(‘ ‘, $nostars), explode(‘ ‘, $stars));

}

static $vowels = array(‘a*’, ‘e*’, ‘i*’, ‘o*’, ‘u*’, ‘ü*’, ‘A*’, ‘E*’, ‘I*’, ‘O*’, ‘U*’, ‘Ü*’);

static $pinyin = array(

1 => array(‘ā’, ‘ē’, ‘ī’, ‘ō’, ‘ū’, ‘ǖ’, ‘Ā’, ‘Ē’, ‘Ī’, ‘Ō’, ‘Ū’, ‘Ǖ’),

2 => array(‘á’, ‘é’, ‘í’, ‘ó’, ‘ú’, ‘ǘ’, ‘Á’, ‘É’, ‘Í’, ‘Ó’, ‘Ú’, ‘Ǘ’),

3 => array(‘ǎ’, ‘ě’, ‘ǐ’, ‘ǒ’, ‘ǔ’, ‘ǚ’, ‘Ǎ’, ‘Ě’, ‘Ǐ’, ‘Ǒ’, ‘Ǔ’, ‘Ǚ’),

4 => array(‘à’, ‘è’, ‘ì’, ‘ò’, ‘ù’, ‘ǜ’, ‘À’, ‘È’, ‘Ì’, ‘Ò’, ‘Ù’, ‘Ǜ’),

5 => array(‘a’, ‘e’, ‘i’, ‘o’, ‘u’, ‘ü’, ‘A’, ‘E’, ‘I’, ‘O’, ‘U’, ‘Ü’)

);

list(, $word, $tone) = $match;

# Add star to vowelcluster

$word = strtr($word, $accentmap);

# Replace starred letter with accented

$word = str_replace($vowels, $pinyin[$tone], $word);

return $word;

}

}

php 多音字,PHP多音字拼音处理方案相关推荐

  1. 汉字转拼音技术方案讨论

    汉字转拼音技术方案讨论   将汉字转化成拼音的应用需求有很多,例如:1.在搜索引擎输入框的智能纠错上,将"刘德花"自动纠正成"刘德华";2.按照拼音检索电话本. ...

  2. win7配色方案_自制的基于rime的简体拼音输入方案,尽可能接近搜狗拼音

    简介 在linux端,很多拼音输入法有少许 bug 或卡顿,或功能不全,所以接触了 rime ,然而自带的朙月拼音和袖珍简化字拼音均不是很不是很理想,但是探索过程中发现很多很好的开源项目提供词库,而 ...

  3. android多音字排序,Android拼音排序

    释放双眼,带上耳机,听听看~! package com.example.f; import java.util.Comparator; import net.sourceforge.pinyin4j. ...

  4. [小狼毫]安装,现成的拼音配置方案

    RIME是一个多平台,开源的一款强大的输入法框架,支持很多输入法,只要配置好方案即可(软件提供好十来种方案,为了用起来符合个人习惯,可设置用户文件夹,很方便进行自定义,详情可自行百度) 我在此是分享现 ...

  5. Pinyin4jUtil 验证姓名与拼音是否一致,自持多音字。

    前几天做了个报名秒杀功能,用户需要输入:                 姓,名,姓拼音,名拼音         中间使用到了pinyin4J, 记录一下. 导入pinyin4j-2.5.0.jar ...

  6. Java pinyin4j 汉字转拼音包括——多音字

    Java汉字转拼音(包括多音字) 有个需求需要把汉字转拼音,我的小伙伴推荐用Unicode官方的包:下载有些慢. 实际中用了Java工具包:pinyin4j解决 可以转汉字,多音字,多音字的地方要求不 ...

  7. 汉字转拼音,一二级词库,不支持多音字

    GB2312标准共收录6763个汉字,其中一级汉字3755个,二级汉字3008个. 分区表示  GB 2312中对所收汉字进行了"分区"处理,每区含有94个汉字/符号.这种表示方式 ...

  8. pinyin4j把中文句子(含有多音字字母)转成拼音(二维数组递归求所有组合情况返回list)算法实现!...

    介绍 Pinyin4j是一个流行的Java库,支持中文字符和拼音之间的转换.拼音输出格式可以定制,然而真正的把含有多音字.数字.字母的中文句子转成拼音得到所有的组合情况却有很大难度,我看过很多有关博客 ...

  9. pinyin4j把中文句子(含有多音字字母)转成拼音(二维数组递归求所有组合情况返回list)算法实现!

    介绍 Pinyin4j是一个流行的Java库,支持中文字符和拼音之间的转换.拼音输出格式可以定制,然而真正的把含有多音字.数字.字母的中文句子转成拼音得到所有的组合情况却有很大难度,我看过很多有关博客 ...

最新文章

  1. drbd配置文件_Linux数据安全工具:数据镜像软件DRBD的安装与配置
  2. ConcurrentHashMap介绍
  3. python pandas.DataFrame.values和pandas.DataFrame.columns的用法
  4. C++之前置自增与后置自增
  5. Problem F: 结构体--学生信息排序
  6. 浅谈 Python 中的 __init__ 和 __new__
  7. C#图解教程读书笔记(结构)
  8. 使用GDB调试产生多进程的程序
  9. 区块链 Fisco bcos 智能合约(18)-FISCO BCOS的速度与激情:性能优化方案最全解密
  10. android与php mysql_手把手教你android通过PHP操作Mysql(1)
  11. 共空间模式算法(CSP)
  12. win7从光盘进入修复计算机,怎么用光盘修复win7_win7如何用光盘修复系统
  13. 微信小程序开发费用一览表 微信小程序制作费用是多少钱
  14. c语言 游程编码,简单的行程编码-C语言实现
  15. OCR证件识别技术的功能特点
  16. DJI AirWorks|赛尔无人机携手大疆航测生态布局全球市场
  17. Eclipse 搭配 MTJ 或 EclipseMe 而无法 预处理 的解决办法
  18. minicom指令_Linux系统minicom命令详解
  19. 鸿蒙投智慧屏交互,鸿蒙初体验:荣耀智慧屏跨系统交互构建新生态
  20. 高可靠性领域如何选取处理器系统和ADC/DAC?

热门文章

  1. 运营商不限流量套餐存陷阱,其实流量是有限的
  2. 读取“手机商品销售数据.xlsx”的文件,使用pyecharts绘制出该表2015年-2022年手机店A和手机店B的销售时间轮播折线图
  3. 知网博士论文校外查找下载方法
  4. 我的天哪, 什么是SOA架构
  5. 极客窝技术交流会-0930
  6. Nodejs+Vue wzry项目 开发记录
  7. android红心点赞动画,Android控件实现直播App点赞飘心动画
  8. 深入理解德语动词变化(二)
  9. 使用python制作一个简易的远控终端
  10. java计算机毕业设计个人收支管理系统MyBatis+系统+LW文档+源码+调试部署