簡體   English   中英

在 PHP 中查找重復的單詞而不指定單詞本身

[英]Finding repeated words in PHP without specifying the word itself

我一直在為我想做的項目考慮一些事情,我不是高級用戶,我只是在學習。 不知道這是否可能:

假設我們有 100 個 html 文檔,其中包含許多表格和文本。

問題一是:有沒有可能分析所有這些文本並找到重復的單詞並計算它?

是的,可以用一些函數來做,但問題是:如果我們不知道會找到的詞怎么辦? 也就是說,我們必須告訴代碼一個詞的含義。

例如,假設一個詞是七個字符的並集,其想法是找到其他類似的模式並提及它。 什么是最好的方法來做到這一點?

非常感謝您提前。

例子:

搜索: 下一個短語的五個字符模式:

正文一:

“需要大海才能不破裂”

正文二:

“海洋是咸水體”

結果

Takes 1 
Break 1
water 1
Ocean 2

在此先感謝您的幫助。

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);

OUTPUT

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的評論更新以處理基本標點符號。

使用內置函數的另一種方法也忽略短詞:

   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)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM