文字列から一般的な単語を抽出する関数です。3つのパラメータを取ります。文字列、ストップワード配列、およびキーワードがカウントされます。txtファイルを配列に取り込むphp関数を使用してtxtファイルからstop_wordsを取得する必要があります
$ stop_words = file('stop_words.txt'、FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);
$ this-> extract_common_words($ text、$ stop_words)
このファイルstop_words.txtをプライマリストップワードファイルとして使用することも、独自のファイルを作成することもできます。
function extract_common_words($string, $stop_words, $max_count = 5) {
$string = preg_replace('/ss+/i', '', $string);
$string = trim($string); // trim the string
$string = preg_replace('/[^a-zA-Z -]/', '', $string); // only take alphabet characters, but keep the spaces and dashes too…
$string = strtolower($string); // make it lowercase
preg_match_all('/\b.*?\b/i', $string, $match_words);
$match_words = $match_words[0];
foreach ( $match_words as $key => $item ) {
if ( $item == '' || in_array(strtolower($item), $stop_words) || strlen($item) <= 3 ) {
unset($match_words[$key]);
}
}
$word_count = str_word_count( implode(" ", $match_words) , 1);
$frequency = array_count_values($word_count);
arsort($frequency);
//arsort($word_count_arr);
$keywords = array_slice($frequency, 0, $max_count);
return $keywords;
}