计算句子平均字数

  • 本文关键字:句子 计算 php
  • 更新时间 :
  • 英文 :


在我的PHP项目中,我试图计算每句话的平均字数。

当我输入几个句子时,一切都正常运行。

句子:

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

"wordsPerSentences": "9.0"

,当我只输入一个句子且没有句号时,平均值为"0"。

内容:

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

结果:

"wordsPerSentences": "0.0"

问题是,当我输入'句号'空格时,它会在单词后添加分数或逗号空格

内容:

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

结果:

"wordsPerSentences": "10.0"

我怎样才能在其他条件中涵盖这种情况?

EDIT:除了有"逗号"在一个句子中只有两个单词之间,它返回&;1&;,并且应该&;2&;。

我代码:

$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);

您可以使用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   ');

它将计算所有单词,并忽略换行/空格。

可以使用str_word_count

echo str_word_count('Cassieres Werk zur der verbindet die des mit an.');

下面的函数将返回每句话的平均字数。我希望这将解决你的问题。

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

编辑我重写了这个函数,用"one_answers"?"。

最新更新