[英]Most used words in text with php
我在stackoverflow上找到了下面的代碼,它可以很好地找到字符串中最常見的單詞。 但是,我可以排除對“a,if,you,have等”等常用詞的統計嗎? 或者我必須在計數后刪除元素? 我該怎么做? 提前致謝。
<?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>';
?>
這是一個從字符串中提取常用單詞的函數。 它需要三個參數; 字符串,停止字數組和關鍵字計數。 你必須使用PHP函數從txt文件中獲取stop_words,將txt文件轉換為數組
$ 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;
}
沒有其他參數或本機PHP函數可以傳遞要排除的單詞。 因此,我只會使用您擁有的內容並忽略str_word_count
返回的自定義單詞str_word_count
。
您可以使用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
)
但你必須自己照顧大小寫。 這里最簡單的方法是事先將文本轉換為小寫。
這是我使用內置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 (可選) - 從數組中過濾掉的單詞列表,默認為空數組。
string $ limit (可選) - 限制返回的單詞數,默認值為5 。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.