2010-04-29 137 views
7

以此字符串爲例:「將在明天在倫敦和明天在肯特見到你」。php - 如何將字符串轉換爲其關鍵字的關聯數組

如何將它轉換爲包含該關鍵字作爲關鍵字的關聯數組,同時優選錯過的常用詞,像這樣:

陣列([明天] => 2 [倫敦] => 1 [肯特] => 1)

任何幫助非常感謝。

回答

0

用字的黑名單不包含

$str = 'will see you in London tomorrow and Kent the day after tomorrow'; 
$skip_words = array('in', 'the', 'will', 'see', 'and', 'day', 'you', 'after'); 
// get words in sentence that aren't to be skipped and count their values 
$words = array_count_values(array_diff(explode(' ', $str), $skip_words)); 

print_r($words); 
7

我會說你可以:

  • 的字符串分割成單詞
  • us e array_filte r只保留行(即話)你想
    • 回調函數將不得不爲所有非有效字
  • 和,然後,將得到的單詞列表上使用array_count_values返回false
    • 將計多少次每個字是本字陣列中



編輯:和,只是爲了好玩,這裏有一個簡單的例子:

首先,字符串,這被分解成字:

$str = "will see you in London tomorrow and Kent the day after tomorrow"; 
$words = preg_split('/\s+/', $str, -1, PREG_SPLIT_NO_EMPTY); 
var_dump($words); 

它可以幫助您:

array 
    0 => string 'will' (length=4) 
    1 => string 'see' (length=3) 
    2 => string 'you' (length=3) 
    3 => string 'in' (length=2) 
    4 => string 'London' (length=6) 
    5 => string 'tomorrow' (length=8) 
    6 => string 'and' (length=3) 
    7 => string 'Kent' (length=4) 
    8 => string 'the' (length=3) 
    9 => string 'day' (length=3) 
    10 => string 'after' (length=5) 
    11 => string 'tomorrow' (length=8) 


然後,filteting:

function filter_words($word) { 
    // a pretty simple filter ^^ 
    if (strlen($word) >= 5) { 
     return true; 
    } else { 
     return false; 
    } 
} 
$words_filtered = array_filter($words, 'filter_words'); 
var_dump($words_filtered); 

,輸出:

array 
    4 => string 'London' (length=6) 
    5 => string 'tomorrow' (length=8) 
    10 => string 'after' (length=5) 
    11 => string 'tomorrow' (length=8) 


最後,計數:

$counts = array_count_values($words_filtered); 
var_dump($counts); 

而最終的結果:

array 
    'London' => int 1 
    'tomorrow' => int 2 
    'after' => int 1 


現在,你來從這裏;-)
主要建立,你必須去努力:

  • 更好的爆炸功能,與ponctuation 交易(或在處理這個過濾)
  • 「智能」過濾功能,適合自己需要更好的比我

玩得開心!

+0

快給我。再次舀。 – dnagirl 2010-04-29 18:45:53

+0

'str_word_count'也可能很有趣:http://www.php.net/manual/en/function.str-word-count.php – 2010-04-29 18:55:12

+0

謝謝你的作品。有沒有可能獲得最終結果「int」?即只是自己的號碼 – Steven 2010-04-29 19:00:16

1

你可以有常用詞表,然後通過你的字符串去一個字的時間,檢查它是否在該表存在,如果沒有,那麼它+1添加到您的關聯數組,或者如果它已經存在。

相關問題