保留字符串中的某些短语

时间:2012-02-06 23:48:59

标签: php

下面的代码返回字符串$commentstring中最常出现的单词列表,清除标点符号和数字。它很棒。

然而,口语短语和品牌名称被分解为单个词。我想把它们结合起来。

因此,如果在“薯条”之前出现“法语”这个词,我希望将它们合并为“炸薯条”。我想提出一个像这样的短语列表,如“巧克力片”,“可口可乐”,“老派”等。我怎么能这样做?

$commentstring = str_replace(array('/', '*', ')', '(', '!', '.', ',', ':'), '', $commentstring);

    $words = explode(" ", $commentstring);


    $result = array();

    arsort($words);







foreach($words as $word) {

    if(!is_numeric($word)){
        $result[$word]++;
        arsort($result);
    }

}




    echo "<table>";


        $blacklist = array($submission, 'DESPITE', 'FARE', 'DECENT', 'AMAZING', 'WOULD', 'DISLIKE', 'HATE', 'OKAY', 'JUST', 'NOTHING', 'CURRENTLY', 'BASICALLY', 'BIT', 'COME', 'WANT', 'TOO', 'HERE', 'EATING', 'EAT', 'WAS', 'TRIED', 'TRY', 'MAKES', 'HAS', 'EVEN', 'THINK', 'BETTER', 'YET', 'MORE', 'LOVE', 'WHILE', 'WHERE', 'WRONG', 'FIND', 'EVER', 'RIGHT', 'BEST', 'HAVE', 'WE', 'WAY', 'GREAT', 'NICE', 'HOW', 'RESTAURANTS', 'RESTAURANT', 'EXCELLENT', 'FORGET', 'THEY', 'REALLY', 'MISS', 'VERY', 'LOOKING', 'YOU\'LL', 'CAN\'T', 'WON\'T', 'PLACE', 'ABOUT', 'FOR', 'MOST', 'GOOD', 'CAN', 'GET', 'THING', 'DON\'T', 'BY', 'YOUR', 'BE', 'YOU', 'BRING', 'THAT\'S', 'LITTLE', 'OTHER', 'MANAGES', 'ATE', 'ATE', 'EAT', 'SO', 'SOMEHOW', 'MAKE', 'ALL', 'UP', 'THEM', 'AS', 'THEM', 'YOU\'RE', 'WILL', 'ONLY', 'IF', 'GO', 'DO', 'I\'VE', 'HAD', 'TO', 'SOME', 'FOOD', 'THIS','DOES', 'NOT', 'IT.', 'IT,', 'SEEM', 'END', 'THERE\'S', 'WHETHER', 'DOUBT', 'WHAT', 'WHICH', 'RECOMMEND', 'THE', 'IS', 'A', 'IT\'S', 'OUT', 'JAN', 'IT', 'IT', 'IT', 'LIKE', 'THAN', 'WITH', 'SEEMS', 'WHICH', 'THAT', 'SAY', 'AT', 'ON', 'AN', 'BUT', 'APART', 'STILL', 'ARE', 'OR', 'TEST', 'IN', 'IT', 'AND', 'SET', 'TO', 'NO', 'OF', '', 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z', 'AA', 'BB', 'CC', 'DD', 'EE', 'FF', 'GG', 'HH', 'II', 'JJ', 'KK', 'LL', 'MM', 'NN', 'OO', 'PP', 'QQ', 'RR', 'SS', 'TT', 'UU', 'VV', 'WW', 'XX', 'YY', 'ZZ');


foreach($result as $word => $count1)
{
    if (in_array($word, $blacklist)) continue;


    echo '<tr>';    
    echo '<td>';
    echo "$word";
    echo '</td>';

    echo '<td>';
    echo "$count1 ";
    echo '</td>';

    echo '</tr>';

    }

    echo "</table>";

1 个答案:

答案 0 :(得分:0)

在你的单字foreach循环之后

执行此操作:

$doublewords = array();
foreach ( $words as $i=>$word )
{
    if ( !isset($words[$i+1]) ) continue;
    $combined = strtolower($word." ".$words[$i+1]);
    if ( !isset($doublewords[$combined]) ) $doublewords[$combined] = 0;
    $doublewords[$combined]++;
}

然后$doublewords包含任何双字组合。像“炸薯条”这样的东西比“像这样的”随机组合更频繁地发生,所以它们最终会有更高的数量。

更新以使其适用于特定列表:

$doublewords = array(
    'french fries'=>0,
    'french toast'=>0,
);
foreach ( $words as $i=>$word )
{
    if ( !isset($words[$i+1]) ) continue;
    $combined = strtolower($word." ".$words[$i+1]);
    if ( !isset($doublewords[$combined]) ) continue;
    $doublewords[$combined]++;
}

(ps。也添加了strtolower