[英]How do i find the occurence of words of particular number
大家好,我有一个小问题,假设我有一个字符串
“你好,我叫XYZ”
现在我知道我可以找到单词的长度,因为“Hello”有 5 个字符,而“My”有 2 个字符。 通过使用以下代码
$text = file_get_contents('text.txt'); // $text = 'Hello my name is XYZ';
$words = str_word_count($text, 1);
$wordsLength = array_map(
function($word) { return mb_strlen($word, 'UTF-8'); },
$words
);
var_dump(array_combine($words, $wordsLength));
但是如果我想找到长度为1的单词数为0,长度为2的单词数为2,长度为3的单词数为1,依此类推,直到长度为10的单词数
注意 - 我正在考虑字长直到有一个空格假设数据中有一个日期,比如 20.04.2016 所以它应该告诉我这个数字是长度为 10 的单词是 1。
还有一件事我如何找到字符串中单词的平均长度。 先感谢您
如果您在$wordsLength
数组上使用array_count_values()
,它将给出字符串长度的计数。 如果您使用它和一个模板数组(使用array_fill()
创建),其中元素为 1-10,值为 0。您将获得所有字数的列表...
$counts = array_replace(array_fill(1, 9, 0),
array_count_values($wordsLength));
会给...
Array
(
[1] => 0
[2] => 2
[3] => 1
[4] => 1
[5] => 1
[6] => 0
[7] => 0
[8] => 0
[9] => 0
)
嗨试试这个它适用于日期和特殊字符,表情符号
$text = 'Hello 20.04.2016 🚩 my face😘face is XYZ';
$words =preg_split('/\s+/', $text);
$wordsLength = array_map(
function($word) { return mb_strlen($word, 'UTF-8'); } ,$words);
print_r($words);
//Get Average word Length
$avg=round(array_sum($wordsLength)/count($words),1);
//print Avg
print($avg);
?>
(演示)
$text = ' Hello 20.04.2016 🚩 my incredibleness face😘face is XYZ ';
生成连续可见字符数组
$words = preg_split('/\s+/', $text, 0, PREG_SPLIT_NO_EMPTY);
array (
0 => 'Hello',
1 => '20.04.2016',
2 => '🚩',
3 => 'my',
4 => 'incredibleness',
5 => 'face😘face',
6 => 'is',
7 => 'XYZ',
)
用多字节长度替换可见字符串注意更简单的语法
$wordsLength = array_map('mb_strlen', $words);
array (
0 => 5,
1 => 10,
2 => 1,
3 => 2,
4 => 14,
5 => 9,
6 => 2,
7 => 3,
)
分组和计数长度
$lengthCounts = array_count_values($wordsLength);
array (
5 => 1,
10 => 1,
1 => 1,
2 => 2,
14 => 1,
9 => 1,
3 => 1,
)
建立一组默认值,因为$lengthCounts
可能有间隙
$defaultCounts = array_fill_keys(range(1,10), 0);
array (
1 => 0,
2 => 0,
3 => 0,
4 => 0,
5 => 0,
6 => 0,
7 => 0,
8 => 0,
9 => 0,
10 => 0,
)
过滤计数以删除超出范围的元素/计数
$filteredCounts = array_intersect_key($lengthCounts, $defaultCounts);
array (
5 => 1,
10 => 1,
1 => 1,
2 => 2,
9 => 1,
3 => 1,
)
用找到的计数覆盖默认值以防止输出中出现间隙
$gaplessCounts = array_replace($defaultCounts, $filteredCounts);
array (
1 => 1,
2 => 2,
3 => 1,
4 => 0,
5 => 1,
6 => 0,
7 => 0,
8 => 0,
9 => 1,
10 => 1,
)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.