En mi proyecto PHP, estoy tratando de calcular el promedio de palabras por oración.
Cuando ingreso algunas oraciones, todo funciona como debería.
Frase:
"content": "Cassieres Werk zur der verbindet die des mit an."Resultado:
"wordsPerSentences": "9.0"PERO , cuando ingreso solo una oración y sin punto final, el valor promedio es "0".
Contenido:
"content": "Cassieres Werk zur der verbindet die des mit an"Resultado:
"wordsPerSentences": "0.0"Además , el problema es que cuando ingreso 'punto final' y espacio , se agrega a la partitura o coma y espacio después de la palabra.
Contenido:
"content": "Cassieres Werk zur der, verbindet die des mit an. "Resultado:
"wordsPerSentences": "10.0"¿Cómo puedo cubrir esa condición entre otras?
EDITAR : estas condiciones se resuelven excepto en la que hay "coma" entre solo dos palabras en una oración, devuelve "1" y debería "2".
Mi código:
$tokens = ',.;'; $sentences = []; $chunk = strtok(trim($text), $tokens); // Handle empty $text if (!is_string($chunk)) { return 0; } do { $sentences[] = $chunk; } while ($chunk = strtok($tokens)); $countWords = function (int $carry, string $item) { return $carry + count(array_filter(explode(' ', $item))); }; $totalWords = array_reduce($sentences, $countWords, 0); return $totalWords / count($sentences);Podrías usar str_word_count :
echo str_word_count('Cassieres Werk zur der verbindet die des mit an.'); //9 echo str_word_count('Cassieres Werk zur der verbindet die des mit an. '); //9 echo str_word_count(' Cassieres Werk zur der verbindet die des mit an. '); //9 echo str_word_count(' Cassieres Werk zur der verbindet die des mit an. '); //9 echo str_word_count(' Cassieres Werk zur der verbindet die des mit an ');Contará todas las palabras e ignorará los espacios de descanso/línea.
Puede usar str_word_count.
echo str_word_count('Cassieres Werk zur der verbindet die des mit an.');la siguiente función devolverá el número promedio de palabras por oración. Espero que esto resuelva tu problema.
<?php /** * Average words per sentence * * Assumptions: * - Only space character is used to separate words. * - Only '?' and '.' are used to separate sentences. * - Special characters ',', ';', '-' are removed from text. * * @author Jawira Portugal * @license do whatever you want */ function str_average(string $text) { // Removing "not word" characters in $text $special = [',', ';', '-']; $text = str_replace($special, ' ', $text); $tokens = '.?'; $chunk = strtok(trim($text), $tokens); // Handle empty $text if (!is_string($chunk)) { return 0; } $sentences = []; do { $sentences[] = $chunk; } while ($chunk = strtok($tokens)); $countWords = function (int $carry, string $item) { return $carry + count(array_filter(explode(' ', $item))); }; $totalWords = array_reduce($sentences, $countWords, 0); return $totalWords / count($sentences); } echo str_average(''), PHP_EOL; // 0 echo str_average(' , '), PHP_EOL; // 0 echo str_average("Hello world, this is a test..."), PHP_EOL; // 6 echo str_average("Hello world? this is a test..."), PHP_EOL; // 3 echo str_average("Cassieres Werk zur der verbindet die des mit an."), PHP_EOL; // 9 echo str_average("Cassieres Werk zur der verbindet die des mit an"), PHP_EOL; // 9 echo str_average("Cassieres Werk zur der, verbindet die des mit an. "), PHP_EOL; // 9 echo str_average("...Hello world. foo bar baz? One two three four. "), PHP_EOL; // 3EDITAR Reescribí la función para dividir oraciones con "." y "?".