2009-04-13 81 views
2

我有句话,例如如何将句子的单词组合成组合术语?

去年,John Doe搬到了纽约。

现在我分裂句成单个的词语,我得到:

阵列(“约翰”,“李四”,“感动”,“对”,“新”,“纽约” ,'last','year')

这很容易。但是,我想结合单个单词来获得所有组成的术语。如果组成的术语是有意义的,我不希望所有这些都是。该操作的结果应该是这样的:

约翰,李四,李四,感动,感动李四,李四移动,于迁,能源部搬到...

的单词应该按照k个部分的限制组成。在上面的例子中,限制是3.所以一个术语最多可以包含3个单词。

问题:我怎样才能在PHP中编写组合?如果我有一个函数将输入的句子作为输入,并将所有项作为输出给出一个数组,那就太好了。

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

回答

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));
+0

非常感谢您!一个函数,它给出一个数组作为输出的条件。这些术语甚至按部件的数量排序(前1个字,然后2个字,...)。完善! – caw 2009-04-13 09:41:12

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)); 
    } 
}