【问题标题】:Get the first five sentences from the text从文本中获取前五个句子
【发布时间】:2018-04-27 02:04:32
【问题描述】:

请告诉我,在 PHP 上如何从下面的文本中获取前五个句子?

西塞罗著名的演讲反对他的!政治对手卢修斯·塞尔吉乌斯·卡蒂利娜。 Погода сегодня хорошая!

偶尔会针对类型样本采取第一个针对 Catiline 的演说:quo usque tandem abutere, Catilina, patientia nostra? Quam diu etiam furor iste tuus nos eludet?西塞罗写信。也可能不是。

【问题讨论】:

  • 你能告诉我们你尝试了什么吗?如何定义一个句子?它应该以“。”,“!”结尾或者 ”?” ?再想一想,先做一些实验。
  • 我试图通过正则表达式(使用函数preg_match)将句子拉到一个数组中,但是我做不到。
  • preg_match 返回 true 或 false 但它不能返回任何索引或长度。如果要对句子进行子串化,则需要索引和长度。
  • preg_match 有第三个参数,结果写入的地方

标签: php


【解决方案1】:

不确定这是否适合您的需求,但在爆炸手册中有一个“多重爆炸”功能。

function multiexplode ($delimiters,$string) {

    $ready = str_replace($delimiters, $delimiters[0], $string);
    $launch = explode($delimiters[0], $ready);
    return  $launch;
}

$text = "Cicero famously orated against his! Political opponent Lucius Sergius Catilina. Погода сегодня хорошая!

Occasionally the first Oration against Catiline is taken for type specimens: quo usque tandem abutere, Catilina, patientia nostra? Quam diu etiam furor iste tuus nos eludet? Cicero writing letters. Or maybe not.";

$exploded = multiexplode(array(".", "!", "?"),$text);

print_r(array_slice($exploded,0,5));

然后我使用array_slice来获取数组的前五项。

【讨论】:

    【解决方案2】:

    用非英语字符和句子的模糊定义来解析有点困难,但下面的代码应该可以进行调整。也许有一些小的调整。它最初是由 Blue 先生在上面评论的 Here 找到的。我已经测试了几次,效果很好。

    Function stripSentence($Text, $Number) {
            $Stripped = preg_replace('/\s+/',' ',strip_tags($Text));
            $Sentences = preg_split('/(\.|\?|\!)(\s)/',$Stripped);
            If (COUNT($Sentences) <= $Number) {
                Return $Stripped;
            } Else {
                $Stop = 0;
                ForEach($Sentences AS $i => $Sentence) {
                    $Stop += StrLen($Sentence);
                    If ($i >= $Number - 1) {
                        Break;
                    }
                }
                $Stop += ($Number * 2);
                Return Trim(SubStr($Stripped, 0, $Stop));
            }
        }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2016-06-24
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-07-19
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多