2

我有一句话,例如

John Doe 去年搬到了纽约。

现在我将句子分成单个单词,我得到:

array('John', 'Doe', 'move', 'to', 'New', 'York', 'last', 'year')

这很容易。但是后来我想组合单个单词来获得所有组合的术语。如果组合的术语有意义,那么我想得到所有这些。该操作的结果应如下所示:

约翰,能源部,约翰能源部,移动,能源部移动,约翰能源部移动,到,移动到,能源部移动到......

单词应该由 k 部分的限制组成。在上面的示例中,限制为 3。因此一个术语最多可以包含 3 个单词。

问题:如何在 PHP 中编写组合代码?如果我有一个函数,它将一个句子作为输入并给出一个包含所有术语的数组作为输出,那就太好了。

我希望你能帮助我。提前致谢!

4

2 回答 2

4

每个构图都将由起点和长度定义 - 只需循环即可。

PHP 不会一直为您提供帮助,但它确实有一些方便的功能。

$words = explode(" ", $sentence);
for ($start = 0; $start < count($words); $start++) //starting point
{
   //try all possible lengths
   //limit = max length
   //and of course it can't overflow the string
   for ($len = 1; $len <= $limit && $len <= count($words)-$start; $len++)
   {
      //array_slice gets a chunk of the array, and implode joins it w/ spaces
      $compositions[] = implode(" ", array_slice($words, $start, $len));
   }
}
于 2009-04-13T00:26:03.883 回答
2

如果您已经拥有将单词拆分为数组的代码,则此函数将让您选择您希望短语最长的时间,并返回一个包含短语的数组数组。

function getPhrases($array, $maxTerms = 3) {
    for($i=0; $i < $maxTerms; $i++) { //Until we've generated terms of all lengths
         for($j = 0; $j < (sizeof($array) - $i); $j++) { //Until we've iterated as far through the array as we should go
             $termArray[] = array(array_slice($array, $j, ($i+1))); //Add this part of the array to the array
         }
    }
    return $termArray;
}

//Usage example

$newarray = explode(" ", "This is a pretty long example sentence");
print_r(getPhrases($newarray));
于 2009-04-13T00:41:07.370 回答