【问题标题】:How to combine words of a sentence to composed terms?如何将句子中的单词组合成组合词?
【发布时间】:2010-10-19 01:35:06
【问题描述】:

我有一句话,比如

John Doe 去年搬到了纽约。

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

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

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

John,Doe,John Doe,移动,Doe 移动,John Doe 移动,到,移动到,Doe 移动到 ...

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

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

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

【问题讨论】:

    标签: php nlp semantics composition


    【解决方案1】:

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

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

    【讨论】:

      【解决方案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));

      【讨论】:

      • 非常感谢!一个函数,它给出一个以术语作为输出的数组。这些术语甚至按部分的数量排序(前 1 个单词,然后是 2 个单词,...)。完美!
      • $t = count($array); for($i=0; $i
      • 抱歉,这可能是个愚蠢的问题,但你的代码是做什么的,OIS?
      猜你喜欢
      • 2020-08-30
      • 2011-09-14
      • 1970-01-01
      • 1970-01-01
      • 2011-04-16
      • 1970-01-01
      • 2019-08-20
      • 1970-01-01
      • 2012-08-20
      相关资源
      最近更新 更多