PHP 实现自动摘要
PHP 实现自动摘要的方法
自动摘要是从文本中提取关键信息或生成简短摘要的技术。以下是几种常见的实现方法:
基于关键词提取的方法
使用分词工具或正则表达式提取关键词,然后组合成摘要。例如使用 explode 或 preg_split 分割文本:
$text = "这是一段需要摘要的文本,包含多个句子。";
$keywords = ["摘要", "文本", "句子"];
$sentences = preg_split('/[。!?]/u', $text, -1, PREG_SPLIT_NO_EMPTY);
$summary = "";
foreach ($sentences as $sentence) {
foreach ($keywords as $keyword) {
if (strpos($sentence, $keyword) !== false) {
$summary .= $sentence . "。";
break;
}
}
if (strlen($summary) > 50) break; // 控制摘要长度
}
基于句子权重的方法
计算句子权重(如词频、位置等),选择权重高的句子作为摘要:
function generateSummary($text, $maxLength = 200) {
$sentences = preg_split('/[。!?]/u', $text, -1, PREG_SPLIT_NO_EMPTY);
$wordCounts = array_count_values(str_word_count($text, 1));
$scoredSentences = [];
foreach ($sentences as $i => $sentence) {
$words = str_word_count($sentence, 1);
$score = 0;
foreach ($words as $word) {
$score += $wordCounts[$word] ?? 0;
}
$scoredSentences[$i] = $score / count($words); // 平均词频
}
arsort($scoredSentences);
$summary = '';
foreach (array_keys($scoredSentences) as $i) {
if (strlen($summary) + strlen($sentences[$i]) < $maxLength) {
$summary .= $sentences[$i] . '。';
}
}
return $summary;
}
使用现成的库或API
可以集成第三方库如 PHP-TextAnalysis 或调用API(如阿里云NLP):
// 使用PHP-TextAnalysis示例
require 'vendor/autoload.php';
use TextAnalysis\Tokenizers\GeneralTokenizer;
use TextAnalysis\Summarizers\LexRankSummarizer;
$text = "长文本内容...";
$summarizer = new LexRankSummarizer();
$summary = $summarizer->summarize($text, 3); // 提取3句
处理中文文本的注意事项
中文文本需要特殊处理:
- 使用
mb_系列函数处理多字节字符 - 考虑使用中文分词工具如 SCWS 或 Jieba-PHP
- 正则表达式添加
u修饰符支持UTF-8
// 中文分词示例(需安装分词扩展)
$so = scws_new();
$so->send_text("中文文本内容");
while ($tmp = $so->get_result()) {
// 处理分词结果
}
$so->close();
性能优化建议
对于长文本处理:
- 缓存中间结果
- 设置处理超时时间
- 限制处理的文本长度
- 考虑使用队列异步处理
以上方法可根据具体需求组合或调整,关键是根据应用场景平衡准确性和性能。







