【问题标题】:Finding repeated words in PHP without specifying the word itself在 PHP 中查找重复的单词而不指定单词本身
【发布时间】:2012-12-11 17:42:07
【问题描述】:

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

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

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

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

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

非常感谢您。

例子:

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

文字一:

“大海不破”

正文二:

“海洋是咸水体”

结果

Takes 1 
Break 1
water 1
Ocean 2

提前感谢您的帮助。

【问题讨论】:

标签: php regex repeat words


【解决方案1】:
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 的评论更新以处理基本标点符号。

【讨论】:

  • 您可能想要修剪诸如!?等字符。
  • 感谢@sberry 非常有帮助!
【解决方案2】:

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

   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)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-12-14
    • 2021-12-13
    • 1970-01-01
    • 2012-10-01
    • 2015-11-17
    • 2012-08-09
    • 2021-05-07
    • 1970-01-01
    相关资源
    最近更新 更多