我想在句子中找到单词的位置和频率。
例如 :
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))
但如何索引获取位置? 谢谢你:))
答案 0 :(得分: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 :(得分: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>';
}