3

我在 stackoverflow 上找到了下面的代码,它可以很好地找到字符串中最常见的单词。但是我可以排除对“a, if, you, have, etc”等常用词的计算吗?还是我必须在计数后删除元素?我该怎么做?提前致谢。

<?php

$text = "A very nice to tot to text. Something nice to think about if you're into text.";


$words = str_word_count($text, 1); 

$frequency = array_count_values($words);

arsort($frequency);

echo '<pre>';
print_r($frequency);
echo '</pre>';
?>
4

4 回答 4

11

这是一个从字符串中提取常用词的函数。它需要三个参数;字符串、停用词数组和关键字计数。您必须使用将 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;
}
于 2011-10-30T12:47:32.483 回答
4

这是我使用内置 PHP 函数的解决方案:

most_frequent_words — 查找字符串中出现频率最高的单词

function most_frequent_words($string, $stop_words = [], $limit = 5) {
    $string = strtolower($string); // Make string lowercase

    $words = str_word_count($string, 1); // Returns an array containing all the words found inside the string
    $words = array_diff($words, $stop_words); // Remove black-list words from the array
    $words = array_count_values($words); // Count the number of occurrence

    arsort($words); // Sort based on count

    return array_slice($words, 0, $limit); // Limit the number of words and returns the word array
}

返回数组包含字符串中出现频率最高的单词。

参数 :

string $string - 输入字符串。

array $stop_words (optional) - 从数组中过滤掉的单词列表,默认为空数组。

string $limit (optional) - 限制返回的字数,默认5

于 2017-10-22T13:20:58.233 回答
2

没有额外的参数或原生 PHP 函数可以传递单词来排除。因此,我将只使用您拥有的内容并忽略str_word_count.

于 2010-07-04T16:40:44.343 回答
2

您可以使用以下方法轻松完成此操作array_diff()

$words = array("if", "you", "do", "this", 'I', 'do', 'that');
$stopwords = array("a", "you", "if");

print_r(array_diff($words, $stopwords));

 Array
(
    [2] => do
    [3] => this
    [4] => I
    [5] => do
    [6] => that
)

但是你必须自己处理小写和大写。这里最简单的方法是预先将文本转换为小写。

于 2010-07-04T16:47:19.000 回答