gpt4 book ai didi

字符串中出现次数最多的 PHP 单词

转载 作者:行者123 更新时间:2023-12-04 04:42:32 26 4
gpt4 key购买 nike

我应该在句子中找到出现最多的单词。

这是我尝试过的,但不起作用。

<?php
$str = "Hello friend, Hello good good today!";
$time=array();
$cnt=str_word_count($str, 1);
$times=reset($cnt);
$count=0;
foreach($cnt as $val){
$times=$val;
foreach($cnt as $val){
if($times===$val){
$count++;
$times=$times . $count;
}
}
$count=0;
}
print_r($cnt);
print_r($times);

最佳答案

<?php
$str = "Hello friend, Hello good good today!";
$count = array();
$words = array();
$cnt = str_word_count($str, 1);
foreach ($cnt as $val){
$i = 0;
$term = false;
foreach ($words as $word){
if ($word === $val){
$count[$i]++;
$term = true;
break;
}
$i++;
}
if ($term)
continue;
$words[$i] = $val;
$count[$i] = 1;
}
print_r($cnt);
print_r('<br/>');
$max = -1;
$resultWords = array();
$resultCount = array();
$i = 0;
foreach ($count as $c){
if ($max == $c){
$resultWords[] = $words[$i];
$resultCount[] = $c;
}else if ($max < $c){
$resultWords = array();
$resultCount = array();
$resultWords[] = $words[$i];
$resultCount[] = $c;
$max = $c;
}
$i++;
}
foreach ($resultWords as $result){
print_r($result.' '.$max.'<br/>');
}
?>

尝试使用我上面的代码。希望它会起作用。如果出现次数最多的词只有一个词,则将显示该词以及该词的出现次数。如果有多个单词,则所有单词将显示为出现次数。

关于字符串中出现次数最多的 PHP 单词,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18670825/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com