改变随机句子的顺序

时间:2015-12-24 10:13:28

标签: php

我有一个长文本(3600个句子),我想改变随机句子的顺序。有一些简单的PHP脚本可以改变句子的顺序吗?

2 个答案:

答案 0 :(得分:5)

你可以像这样完成它。在句子的末尾分解一个字符串,例如句号。使用shuffle函数对数组进行随机播放。然后内爆字符串,添加完整的止损。

输出类似于:

Hello, this is one sentence. This is a fifth. This is a forth. This is a second.. THis is a third

$sentences = 'Hello, this is one sentence. This is a second. THis is a third. This is a forth. This is a fifth.';

$sentencesArray = explode('.', $sentences);
array_filter($sentencesArray);
shuffle($sentencesArray);

$sentences = implode('.', $sentencesArray);


var_dump($sentences);

答案 1 :(得分:2)

我构建了一个解决方案,解决了以“。”,“!”结尾的句子的问题。要么 ”?”。我注意到在shuffling中包含句子数组的最后一部分并不是一个好主意,因为最后一部分永远不会以我们分裂的特定字符结束:

“嗨。|你好。|”

我希望你明白这个主意。所以我洗掉除了最后一个之外的所有元素。我分别为“。”,“?”和“!”做了工作。

你应该知道“......”,“?!”,“!!! 11 !! 1 !!”会造成很大的麻烦。 :):)

<?php
function randomizeOrderOnDelimiter($glue,$sentences){

    $sentencesArray = explode($glue, $sentences);

    // Get out the items to shuffle: all but the last.
    $work = array();
    for ($i = 0; $i < count($sentencesArray)-1; $i++) {
        $work[$i] = $sentencesArray[$i];
    }

    shuffle($work);  // shuffle them

    // And put them back.
    for ($i = 0; $i < count($sentencesArray)-1; $i++) {
        $sentencesArray[$i] = $work[$i];
    }

    $sentences = implode($glue, $sentencesArray);
    return $sentences;
}

$sentences = 'Hello, this is one sentence. This is a second. THis is a third. This is a forth. This is a fifth. Sixth is imperative! Is seventh a question? Eighth is imperative! Is ninth also a question? Tenth.';
$sentences = randomizeOrderOnDelimiter('.', $sentences);
$sentences = randomizeOrderOnDelimiter('?', $sentences);
$sentences = randomizeOrderOnDelimiter('!', $sentences);
var_dump($sentences);

?>