2014-09-21 99 views
2

我想找到句子中單詞的位置和頻率。 例如: You should eat two bananas before lunch and eat two before your dinner and then consume one banana.找到句子中單詞的位置和頻率

,所以我會得到的結果: You -> 1 -> position : 1 Should -> 1 -> position : 2 eat -> 2 -> position : 3, 9

對於得到的頻率,我可以使用 array_count_values(str_word_count($str, 1))

但如何索引獲得位置? 謝謝:)

回答

2

那麼,使用你目前的功能,你可以使用一個foreach循環,然後收集它們。使用爆炸並使用他們的指數+ 1 Example

$str = 'You should eat two bananas before lunch and eat two before your dinner and then consume one banana.'; 

$count = array_count_values(str_word_count($str, 1)); 
$data = array(); 
// gather them first 
foreach(explode(' ', $str) as $key => $value) { 
    $value = str_replace('.', '', $value); 
    $key = $key + 1; 
    $data[$value]['positions'][] = $key; 
    $data[$value]['count'] = $count[$value]; 
} 

?> 

<?php foreach($data as $word => $info): ?> 
    <p><?php echo "$word -> $info[count] -> Position: " . implode(', ', $info['positions']); ?></p> 
<?php endforeach; ?> 
1
$string = 'You should eat two bananas before lunch and eat two before your dinner and then consume one banana'; 
$array = explode (' ' , $string) ; 
$frequency = array_count_values ($array); 

    foreach ($frequency as $key => $value) 
    { 
     echo $key.' -> '.$value.' -> position : '.(array_search($key ,$array)+1).'</br>'; 
    } 
相關問題