4

我一直在为我想做的项目考虑一些事情,我不是高级用户,我只是在学习。不知道这是否可能:

假设我们有 100 个 html 文档,其中包含许多表格和文本。

问题一是:是否可以分析所有这些文本并找到重复的单词并计算它?

是的,可以使用某些功能,但问题是:如果我们不知道会找到的单词怎么办?也就是说,我们必须告诉代码一个词的含义。

例如,假设一个词是七个字符的并集,想法是找到其他相似的模式并提及它。最好的方法是什么?

非常感谢您提前。

例子:

搜索:下一个短语的五个字符模式:

文字一:

“需要一片海洋才能不破裂”

文字二:

“海洋是咸水体”

结果

Takes 1 
Break 1
water 1
Ocean 2

在此先感谢您的帮助。

4

2 回答 2

8
function get_word_counts($phrases) {
   $counts = array();
    foreach ($phrases as $phrase) {
        $words = explode(' ', $phrase);
        foreach ($words as $word) {
          $word = preg_replace("#[^a-zA-Z\-]#", "", $word);
            $counts[$word] += 1;
        }
    }
    return $counts;
}

$phrases = array("It takes an ocean of water not to break!", "An ocean is a body of saline water, or so I am told.");

$counts = get_word_counts($phrases);
arsort($counts);
print_r($counts);

输出

Array
(
    [of] => 2
    [ocean] => 2
    [water] => 2
    [or] => 1
    [saline] => 1
    [body] => 1
    [so] => 1
    [I] => 1
    [told] => 1
    [a] => 1
    [am] => 1
    [An] => 1
    [an] => 1
    [takes] => 1
    [not] => 1
    [to] => 1
    [It] => 1
    [break] => 1
    [is] => 1
)

编辑
根据@Jack 的评论更新以处理基本标点符号。

于 2012-12-26T04:19:41.407 回答
0

另一种使用内置函数的替代方法也忽略短词:

   function get_word_counts($text) 
   {
        $words = str_word_count($text, 1);
        foreach ($words as $k => $v) if (strlen($v) < 4) unset($words[$k]); // ignore short words
        $counts = array_count_values($words);
        return $counts;
    }
$counts = get_word_counts($text);
arsort($counts);        
print_r($counts);

注意:这假设一个文本块,如果处理一组短语添加foreach ($phrases as $phrase)

于 2021-12-17T20:28:01.050 回答