我有一个代码,可以计算字符串中字母表的频率。我的代码是:
<?php
$str = "iamtheone";
$freq_count = array();
for ($i = 0; $i < strlen($str); $i++) {
$index = $str[$i];
$freq_count[$index]++;
foreach (range('a', 'z') as $char) {
//echo "<pre>".$key . " " . $char."</pre>";
$index = $char;
if (isset($freq_count[$index])) {
} else {
$freq_count[$index] = "0";
}
}
}
echo "<pre>";
print_r($freq_count);
echo "</pre>";
?>
输出为:
Array
(
[i] => 1
[a] => 1
[b] => 0
[c] => 0
[d] => 0
[e] => 2
[f] => 0
[g] => 0
[h] => 1
[j] => 0
[k] => 0
[l] => 0
[m] => 1
[n] => 1
[o] => 1
[p] => 0
[q] => 0
[r] => 0
[s] => 0
[t] => 1
[u] => 0
[v] => 0
[w] => 0
[x] => 0
[y] => 0
[z] => 0
)
现在我希望他们将数组转换为以下格式:
*
* * * * * * * *
a b c d e f g h i j k l m n o p q r s t u v w x y z
说明:星号的数量取决于每个字母表的频率。例如,a
在字符串中仅重复一次,e
在字符串中重复两次,依此类推
我的数组格式正确吗?
如果没有帮助,你的老师不会相信你这么做了,但是:
$str ="iamtheone";
// Calculate the frequency table for all letters
$letters = array_fill_keys(range('a', 'z'), ' ');
$freq_count = array_merge(
$letters,
array_count_values(str_split(strtolower($str)))
);
// Plot the display chart
for ($line = max($freq_count); $line > 0; --$line) {
echo implode(
' ',
array_map(
function ($value) use ($line) {
return ($value >= $line) ? '*' : ' ';
},
$freq_count
)
);
echo PHP_EOL;
}
echo implode(' ', array_keys($lineArray)), PHP_EOL;
演示
以下是我的看法,只需在每个发现的字符上添加一个星号,无需将出现的次数算作一个数字-也可以使用strtolower()转换大写字符并对其进行计数:
$freqCount = array();
$countedStr = 'iamtheone';
// inits the frequency count array
foreach (range('a','z') as $char) {
$freqCount[$char] = '';
}
for($i=0; $i<strlen($str); $i++) {
$index = $countedStr[$i];
// potentially convert to lower case:
// $index = strtolower($countedStr[$i]);
$freqCount[$index] .= '*'; // adds an asterisk to the letter
}