簡體   English   中英

使用PHP在文本正文中查找3-8個單詞常用短語

[英]Find 3-8 word common phrases in body of text using PHP

我正在尋找一種使用PHP在文本體內查找常用短語的方法。 如果在php中不可能,我會對其他可以幫助我完成此操作的網絡語言感興趣。

記憶或速度不是問題。

現在,我能夠輕松找到關鍵字,但不知道如何搜索短語。

我已經編寫了一個PHP腳本, 就在這里。 它首先將源文本拆分為一個單詞數組及其出現次數。 然后,它計算具有指定參數的那些單詞的常見序列。 這是舊代碼,沒有評論,但也許你會發現它很有用。

只使用PHP? 我能想到的最直接的是:

  • 將每個短語添加到數組中
  • 從數組中獲取第一個短語並將其刪除
  • 找到匹配它的短語數量並刪除它們,保持匹配計數
  • 將短語和匹配數推送到新陣列
  • 重復直到初始數組為空

對於正式的CS我是垃圾,但我相信這是n^2復雜性,特別是在最壞的情況下涉及n(n-1)/2比較。 我毫不懷疑有一些更好的方法可以做到這一點,但是你提到效率是沒有問題的,所以這樣做。

代碼如下(我使用了一個新函數, array_keys接受一個搜索參數):

// assign the source text to $text
$text = file_get_contents('mytext.txt');

// there are other ways to do this, like preg_match_all,
// but this is computationally the simplest
$phrases = explode('.', $text);

// filter the phrases
// if you're in PHP5, you can use a foreach loop here
$num_phrases = count($phrases);
for($i = 0; $i < $num_phrases; $i++) {
  $phrases[$i] = trim($phrases[$i]);
}

$counts = array();

while(count($phrases) > 0) {
  $p = array_shift($phrases);
  $keys = array_keys($phrases, $p);
  $c = count($keys);
  $counts[$p] = $c + 1;

  if($c > 0) {
    foreach($keys as $key) {
      unset($phrases[$key]);
    }
  }
}

print_r($counts);

查看它的實際效果: http//ideone.com/htDSC

我想你應該去

str_word_count

$str = "Hello friend, you're
       looking          good today!";

print_r(str_word_count($str, 1));

會給

Array
(
    [0] => Hello
    [1] => friend
    [2] => you're
    [3] => looking
    [4] => good
    [5] => today
)

然后你可以使用array_count_values()

$array = array(1, "hello", 1, "world", "hello");
print_r(array_count_values($array));

哪個會給你

Array
(
    [1] => 2
    [hello] => 2
    [world] => 1
)

一個丑陋的解決方案,因為你說丑陋可以,就是為你的任何一個短語搜索第一個單詞。 然后,一旦找到該單詞,檢查它后面的下一個單詞是否與短語中的下一個預期單詞匹配。 這將是一個循環,只要命中是正數,直到一個單詞不存在或短語完成,它將繼續運行。

簡單,但非常丑陋,可能非常非常慢。

來到這里很晚,但是因為我在尋找類似的事情時偶然發現了這一點,我想我會分享我在2019年登陸的地方:

https://packagist.org/packages/yooper/php-text-analysis

這個圖書館讓我的任務徹底變得微不足道。 在我的情況下,我有一系列搜索短語,我最終分成單個術語,規范化,然后創建兩個和三個字的ngrams。 通過生成的ngrams循環,我能夠輕松地總結特定短語的頻率。

$words   = tokenize($searchPhraseText);
$words   = normalize_tokens($words);
$ngram2  = array_unique(ngrams($words, 2));
$ngram3  = array_unique(ngrams($words, 3));

非常酷的圖書館提供了很多。

如果您想在html文件中進行全文搜索,請使用Sphinx強大的搜索服務器。 文檔在這里

暫無
暫無

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

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