zhu894532094 发表于 2017-3-23 13:04:50

PHP提取摘要

function getSummary($content,$words,$max_desc_len=200){

if(is_array($words)){
$arrwords=$words;
}else{
$arrwords=explode(',',$words);
}
//$arrwords=array('挖掘'=>30,'频繁'=>20);

//如果没有关键词,直接输出前几段
if(count($arrwords)==0){
$output=$content;

//有关键词,输出带关键词的段落
}else{
//将内容拆分成数组
$content=str_replace('\n','[]',$content);
$content=str_replace('.','.[]',$content);
$content=str_replace('。','。[]',$content);
$docs=explode('[]',$content);
$docs=array_filter($docs,'strlen');
//记录每个关键词的在每段出现的次数和每段的权重,按权重排序
$poss=0;
$pos=true;
foreach($docs as $key=>$content){
foreach ( $arrwords as $word) {
while ($pos) {
$pos=mb_strpos ( $content, $word, $poss , 'utf8' );
if($pos===false){
break;
}else{
$pos_words['pos']=$pos;//记录所有的关键词出现的位置
$pos_words['word']=$word;//记录每个位置的关键词
$allpos[$key]['words'][]=$pos_words;//记录段落关键词位置
$allpos[$key]['weight']+=20;

$poss=$pos+1;
$pos=true;
}
}
$poss=0;
$pos=true;
}
$weight[$key]=intval($allpos[$key]['weight']);
}
$weight=array_flip($weight);
krsort($weight);
$weight=array_flip($weight);
foreach($weight as $k=>$v){
$summary[]=$docs[$k];
}

$output=array_slice($summary,0,2);
}
$output=getShort(implode('..',$output),$max_desc_len);
//$output=implode('..',$output);
return $output;
}
页: [1]
查看完整版本: PHP提取摘要