php - 计算单词在 PHP 文本中出现的频率

标签 php

在 php 中,我需要加载一个文件并获取所有单词并回显单词以及每个单词在文本中出现的次数, (我还需要它们按最常用词的降序显示在顶部)★✩

最佳答案

这是一个例子:

$text = "A very nice únÌcÕdë text. Something nice to think about if you're into Unicode.";

// $words = str_word_count($text, 1); // use this function if you only want ASCII
$words = utf8_str_word_count($text, 1); // use this function if you care about i18n

$frequency = array_count_values($words);

arsort($frequency);

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

输出:

Array
(
    [nice] => 2
    [if] => 1
    [about] => 1
    [you're] => 1
    [into] => 1
    [Unicode] => 1
    [think] => 1
    [to] => 1
    [very] => 1
    [únÌcÕdë] => 1
    [text] => 1
    [Something] => 1
    [A] => 1
)

还有 utf8_str_word_count() 函数,如果您需要的话:

function utf8_str_word_count($string, $format = 0, $charlist = null)
{
    $result = array();

    if (preg_match_all('~[\p{L}\p{Mn}\p{Pd}\'\x{2019}' . preg_quote($charlist, '~') . ']+~u', $string, $result) > 0)
    {
        if (array_key_exists(0, $result) === true)
        {
            $result = $result[0];
        }
    }

    if ($format == 0)
    {
        $result = count($result);
    }

    return $result;
}

关于php - 计算单词在 PHP 文本中出现的频率,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2123236/

相关文章:

php - 在 jQuery 弹出窗口中打开 PHP 文件,而不使用 iframe

刷新后 PHP Session 将不起作用

php - MySQL 日期搜索 MM/DD/YYYY 到 MM/DD/YYYY

php - 如何使用 foreach 循环根据所选选项将数据检索到文本区域?

php - 使用 PHP (Windows/Linux) 连接到 SQL 2008 服务器

php - htaccess 文件中使用 cdn 重定向 url

java - 使用改造发送带有一些参数的多部分(文件)

php - TCPDF:Pdf 顶部始终有一个 hr 行

php - 必须加载内存缓存扩展才能使用此后端

PHP PCNTL - pcntl_signal() 的 restart_syscalls 参数有什么作用?