-4

我想使用 PHP 根据文本中重复次数最多的单词自动生成标题。示例:如果单词“PHP”在文本中重复最多,则标题将是:“The text is about PHP”....等等。我不知道该做什么或从哪里开始。

谁能帮我这个?

4

3 回答 3

3

如果我必须为你完成你的家庭作业,我需要在论文中完整注明出处,并且该问题的链接也在所述论文中。

我还要求您实际阅读、理解并尝试运行此代码以使您能够理解它。

//get all the test from the file
$text_from_file = file_get_contents("filename.txt");

//get all the words within that text
$words = str_word_count($text_from_file , 1);

//count up all the unique words within the array
$unique = array_count_values($words);

//sort by most to least frequent
arsort($unique); //arsort required to keep keys and values together

//since we dont know the key values here, we need to use foreach
foreach($unique as $key => $val) {
  echo("The most common word is " . $key . " which occurs " . $val . " times");

  break; //always break after the first echo
}
于 2013-07-02T19:31:45.147 回答
1
<?php
function mostRepeated($string = false, $words_num = 5) {
    $string = strtolower($string);
    // extend this array
    $omit_words = array('the', 'a', 'an', 'in', 'at', 'by', 'of', 'was', 'is', 'he', 'she');

    $words = explode(' ', $string);
    foreach($words as $k => $v) {
        if(in_array($word, $omit_words)) unset($words[$k]);
    }

    $count = array_count_values($words);
    arsort($count);
    $result = array();
    foreach($count as $k => $v) {
       $result[] = $k;
    }

    return $result;
}

$text = 'PHP foo Bar php foO pHp';
$most_repeated_words_array = mostRepeated($text, 3);
print_r($most_repeated_words_array);
?>

输出:

    Array
(
    [0] => php
    [1] => foo
    [2] => bar
)
于 2013-07-02T19:26:29.520 回答
0

使用

print_r( array_count_values(str_word_count($text, 1)) );

会给你所有单词的计数。然后你可以在排序时选择最上面的那个吗?

rsort

会给你一个从高到低的排序数组

于 2013-07-02T19:10:59.130 回答