Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

203
Views
Calcular el promedio de palabras en la oración

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);
over 4 years ago · Santiago Trujillo
3 answers
Answer question

0

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.

over 4 years ago · Santiago Trujillo Report

0

Puede usar str_word_count.

 echo str_word_count('Cassieres Werk zur der verbindet die des mit an.');
over 4 years ago · Santiago Trujillo Report

0

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; // 3

EDITAR Reescribí la función para dividir oraciones con "." y "?".

over 4 years ago · Santiago Trujillo Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!