PHP 实现自动摘要
PHP 实现自动摘要的方法
基于字符串截取的方法
对于简单的摘要需求,可以直接截取字符串的前N个字符。这种方法适用于内容开头部分包含关键信息的情况。
function getSummary($text, $length = 100) {
if (strlen($text) <= $length) {
return $text;
}
return substr($text, 0, $length) . '...';
}
基于句子分割的方法
通过标点符号分割文本为句子,然后选择前几个句子作为摘要。这种方法能保持句子完整性。
function getSentenceSummary($text, $sentences = 2) {
$sentencesArray = preg_split('/(?<=[.?!])\s+/', $text, -1, PREG_SPLIT_NO_EMPTY);
$summary = array_slice($sentencesArray, 0, $sentences);
return implode(' ', $summary) . '...';
}
基于关键词提取的方法
使用TF-IDF算法或简单词频统计提取关键词,然后选择包含关键词的句子作为摘要。
function getKeywordSummary($text, $keywordsCount = 3) {
$words = str_word_count(strtolower($text), 1);
$wordFrequencies = array_count_values($words);
arsort($wordFrequencies);
$keywords = array_slice(array_keys($wordFrequencies), 0, $keywordsCount);
$sentences = preg_split('/(?<=[.?!])\s+/', $text, -1, PREG_SPLIT_NO_EMPTY);
$summarySentences = [];
foreach ($sentences as $sentence) {
foreach ($keywords as $keyword) {
if (stripos($sentence, $keyword) !== false && !in_array($sentence, $summarySentences)) {
$summarySentences[] = $sentence;
break;
}
}
if (count($summarySentences) >= 3) break;
}
return implode(' ', $summarySentences) . '...';
}
使用外部库
对于更复杂的摘要需求,可以使用专门的PHP库:

-
安装PHP-ML库(需要Composer):
composer require php-ai/php-ml -
使用文本摘要算法:

require_once 'vendor/autoload.php';
use Phpml\FeatureExtraction\TfIdfTransformer; use Phpml\Tokenization\WordTokenizer;
function getTfIdfSummary($text, $sentences = 3) { $tokenizer = new WordTokenizer(); $sentencesArray = preg_split('/(?<=[.?!])\s+/', $text, -1, PREG_SPLIT_NO_EMPTY);
$wordsPerSentence = array_map(function($sentence) use ($tokenizer) {
return $tokenizer->tokenize($sentence);
}, $sentencesArray);
$tfIdf = new TfIdfTransformer();
$tfIdf->fit($wordsPerSentence);
$tfIdf->transform($wordsPerSentence);
$sentenceScores = array_map('array_sum', $wordsPerSentence);
arsort($sentenceScores);
$topSentences = array_slice(array_keys($sentenceScores), 0, $sentences);
sort($topSentences);
$summary = array_map(function($index) use ($sentencesArray) {
return $sentencesArray[$index];
}, $topSentences);
return implode(' ', $summary) . '...';
}
#### 处理HTML内容的摘要
如果需要从HTML内容中提取纯文本并生成摘要:
```php
function getHtmlSummary($html, $length = 150) {
$plainText = strip_tags($html);
$plainText = html_entity_decode($plainText);
if (strlen($plainText) <= $length) {
return $plainText;
}
$summary = substr($plainText, 0, $length);
$lastSpace = strrpos($summary, ' ');
if ($lastSpace !== false) {
$summary = substr($summary, 0, $lastSpace);
}
return $summary . '...';
}
这些方法可以根据具体需求选择使用,从简单到复杂提供了不同层次的摘要实现方案。对于内容管理系统或新闻网站,基于关键词或TF-IDF的方法通常能产生更好的摘要效果。






