Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

204
Visualizações
Calculate average words in sentence

In my PHP project I am trying to calculate average words count per sentence.

When I input few sentences everything works as it should.

Sentence:

"content": "Cassieres Werk zur der verbindet die des mit an."

Result:

"wordsPerSentences": "9.0"

BUT, when I input just one sentence and without full stop the average value is "0".

Content:

"content": "Cassieres Werk zur der verbindet die des mit an"

Result:

"wordsPerSentences": "0.0"

Also, problem is that when I input 'full stop' and space it adds to the score or comma and space after the word?

Content:

"content": "Cassieres Werk zur der, verbindet die des mit an. "

Result:

"wordsPerSentences": "10.0"

How can I cover that condition among others?

EDIT: This conditions are solved except the one where there is "comma" between just two words in a sentence, it returns "1", and should "2".

My code:

$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 Respostas
Responde à pergunta

0

You could use 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   ');

It'll count all words, and ignore break/line spaces.

over 4 years ago · Santiago Trujillo Relatório

0

You can use str_word_count.

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

0

the following function will return the average number of words per sentence. I hope this will solve your problem.

<?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

EDIT I rewrote the function to split sentences with "." and "?".

over 4 years ago · Santiago Trujillo Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda