找出单词在句子中的位置和频率


find position and frequency of words in sentences

我想找出单词在句子中的位置和频率。例如:You should eat two bananas before lunch and eat two before your dinner and then consume one banana.

所以我会得到结果:You -> 1 -> position : 1Should -> 1 -> position : 2eat -> 2 -> position : 3, 9

为了获得我可以使用的频率array_count_values(str_word_count($str, 1))

但是如何索引以获取位置呢?谢谢:)

使用当前函数,您可以使用foreach循环,然后收集它们。使用爆炸并使用它们的索引+1。示例:

$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; ?>
$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>';
    }