1

这是我想出的代码行:

function Count($text)
        {    
            $WordCount = str_word_count($text);         

            $TextToArray = explode(" ", $text);
            $TextToArray2 = explode(" ", $text);

            for($i=0; $i<$WordCount; $i++)
            {
                $count = substr_count($TextToArray2[$i], $text);
            }
            echo "Number of {$TextToArray2[$i]} is {$count}";                                                   
        }

所以,这里会发生的是,用户将输入文本、句子或段落。通过使用 substr_count,我想知道单词在数组中出现的次数。不幸的是,输出并不是我真正需要的。有什么建议么?

4

3 回答 3

1

我假设您想要一个带有单词频率的数组。

首先,将字符串转换为小写并从文本中删除所有标点符号。这样,您将不会获得“但是”、“但是”和“但是”的条目,而只会获得具有 3 次或更多用途的“但是”。

其次,使用str_word_count马克贝克所说的第二个参数 2 来获取文本中的单词列表。这可能比我对 preg_split 的建议更有效。

然后遍历数组并将单词的值加一。

foreach($words as $word)
  $output[$word] = isset($output[$word]) ? $output[$word] + 1 : 1;
于 2012-07-25T13:56:30.590 回答
0
$WordCounts = array_count_values(str_word_count(strtolower($text),2));
var_dump($WordCounts);
于 2012-07-25T14:02:52.903 回答
0

如果我正确理解了您的问题,这也应该可以解决您的问题

function Count($text) {
   $TextToArray = explode(" ", $text); // get all space separated words
   foreach($TextToArray as $needle) {
     $count = substr_count($text, $needle); // Get count of a word in the whole text
     echo "$needle has occured  $count times in the text";
   }
}
于 2012-07-25T13:58:16.603 回答