我想计算句子中字符的分数


I want to calculate the score of the characters in a sentence

我有一个句子作为输入。
我希望能够根据构成每个单词的字母计算句子(a=1, b=2, c=3)的总分。

此外,如果句子有一个双字母,i希望将其值加倍。

最后,我想过滤掉与 a-z 不同的字符。

代码(已编辑(

$words = "Try to do this";  
$letters = str_split($words);  
$value = '0 a b c d e f g h i j k l m n o p q r s  u v w x y z';  
$value = explode(' ',$value);  
$value1 = array_flip($value); 
$result = array_intersect($letters, $value);

这是我开始但无法完成的事情,我发布它只是为了看看我的逻辑是否正确!

我重新设计了您的代码并认为这将按预期工作。我已经编辑了这段代码,所以它现在可以正确地解释双分项目。请注意,$double_score_array只有一个字母,但正则表达式{2}指示应连续查看 2 个字母。注释已到位,以解释每个阶段:

// Set the '$words' string.
$words = "Try to do thiis.";
// Set an array for double score items.
$double_score_array = array('i');
// Init the '$raw_results' array
$raw_results = array();    
// Create a '$value_array' using the range of 'a' to 'z'
$value_array = range('a','z');
// Prepend a '0' onto the '$value_array'
array_unshift($value_array, 0);
// Flip the '$value_array' so the index/key values can be used for scores.
$value_array_flipped = array_flip($value_array); 
// Filter out any character that is not alphabetical.
$words = preg_replace('/[^a-zA-Z]/', '', strtolower($words));
// Let's roll through the double score items.
foreach ($double_score_array as $double_score_letter) {
  preg_match('/' . $double_score_letter . '{2}/', $words, $matches);
  $double_score_count = count($matches);
  // With double score items accounted, let's get rid of the double score item to get normal scores.
  $words = preg_replace('/' . $double_score_letter . '{2}/', '', $words);
}
// Split the '$words' string into a '$letters_array'
$letters_array = str_split($words);
// Now let's set the value for the double score items.
$raw_results[] = (($value_array_flipped[$double_score_letter] * 2) * $double_score_count);
// Roll through the '$letters_array' and assign values.
foreach ($letters_array as $letter_key => $letter_value) {
  $raw_results[] = $value_array_flipped[$letter_value];
}
// Filter out the empty values from '$raw_results'.
$filtered_results = array_filter($raw_results);
// Run an 'array_sum()' on the '$filtered_results' to get a final score.
$final_results = array_sum($filtered_results);
// Echo the score value in '$final_results'
echo 'Score: ' . $final_results;
// Dump the '$filtered_results' for debugging.
echo '<pre>';
print_r($filtered_results);
echo '</pre>';

编辑 在评论中,原始海报指出上面的代码不会使分数翻倍。不清楚这一点,因为根据示例,字母i是字母表的第 9 个字母。 所以分数将是9。那么双倍分数不是18吗?或者你的意思是它应该是36意味着两个单独的i项目的分数的两倍?

如果"双倍分数"实际上意味着将两个单独项目的分数加倍,那么只需转到代码的这一部分:

// Now let's set the value for the double score items.
$raw_results[] = (($value_array_flipped[$double_score_letter] * 2) * $double_score_count);

并将2更改为4,以有效地将双字母 ietms 的分数加倍:

// Now let's set the value for the double score items.
$raw_results[] = (($value_array_flipped[$double_score_letter] * 4) * $double_score_count);

另一个编辑 好的,我想我理解原始海报的要求。特别是当他们问,"另外,如果一个句子有一个双字母,我想把它的值加倍。我和其他人将其解释为连续两个字母,例如ii,但似乎如果这两个字母只出现在一个句子中,那么分数就会翻倍。因此,我重新设计了逻辑,以解释句子中出现的任何两个i实例。 由于不清楚如果一个句子中出现超过 2 个i会发生什么,所以我设置了逻辑来解释这样的情况;这些额外的i只得到一个值。添加我的新版本。与上面的第一个版本进行比较和对比。您现在应该能够做任何您需要做的事情。

// Set the '$words' string.
$words = "Try to do thiiis.";
// Set an array for double score items.
$double_score_array = array('i');
// Set a double score multiplier.
$double_score_multiplier = 2;
// Init the '$raw_results' array
$raw_results = array();    
// Create a '$value_array' using the range of 'a' to 'z'
$value_array = range('a','z');
// Prepend a '0' onto the '$value_array'
array_unshift($value_array, 0);
// Flip the '$value_array' so the index/key values can be used for scores.
$value_array_flipped = array_flip($value_array); 
// Filter out any character that is not alphabetical.
$words = preg_replace('/[^a-zA-Z]/', '', strtolower($words));
// Let's roll through the double score items.
$double_score_count = $non_double_count = 0;
foreach ($double_score_array as $double_score_letter) {
  $double_score_regex = sprintf('/%s{1}/', $double_score_letter);
  preg_match_all($double_score_regex, $words, $matches);
  $count = count($matches[0]);
  // We only want to double the score for the first two letters found.
  if ($count >= 2) {
    $double_score_count = 2;
  }
  // This handles the accounting for items past the first two letters found.
  $non_double_count += ($count - 2);
  // This handles the accounting for single items less than the first two letters found.
  if ($count < 2) {
    $non_double_count += $count;
  }
  // With double score items accounted, let's get rid of the double score item to get normal scores.
  $words = preg_replace($double_score_regex, '', $words);
}
// Split the '$words' string into a '$letters_array'
$letters_array = str_split($words);
// Now let's set the value for the double score items.
if ($double_score_count > 0) {
  $raw_results[] = (($value_array_flipped[$double_score_letter] * $double_score_multiplier) * $double_score_count);
}
// And get the values of items that are non-double value.
if ($non_double_count > 0) {
  $raw_results[] = $value_array_flipped[$double_score_letter] * $non_double_count;
}
// Roll through the '$letters_array' and assign values.
foreach ($letters_array as $letter_key => $letter_value) {
  $raw_results[] = $value_array_flipped[$letter_value];
}
// Filter out the empty values from '$raw_results'.
$filtered_results = array_filter($raw_results);
// Run an 'array_sum()' on the '$filtered_results' to get a final score.
$final_results = array_sum($filtered_results);
// Echo the score value in '$final_results'
echo 'Score: ' . $final_results;
// Dump the '$filtered_results' for debugging.
echo '<pre>';
print_r($filtered_results);
echo '</pre>';
// Input string
$str = 'Try to do this';
// Remove irrelevant characters, convert to lowercase
$str = preg_replace('/[^a-z]/', '', strtolower($str));
// Create a function to determine the value of a character
function my_char_value($char) {
    return ord($char) - 96;
}
// Convert the string to an array and apply our function to each element
$arr = array_map('my_char_value', str_split($str));
// Add each array element to determine subtotal
$sum = array_sum($arr);
// Double the sum if two "i"s are present in the string
if (preg_match('/i.*?i/', $str)) {
    $sum *= 2;
}
print $sum;

我找到了更好的解决方案查看此代码

    <?php
    /**
    * Script to calculate the total score of a sentence (a=1, b=2, c=3), according to the letters that form each word. 
    * Also, if a sentence has a double letter i want to double its value.
    * Finally, I want to filter out characters different from a-z. 
    * 
    * Author: Viswanath Polaki
    * Created: 5-12-2013 
    */
    //array to define weights
    $weight = array(
        'a' => 1,
        'b' => 2,
        'c' => 3,
        'd' => 4,
        'e' => 5,
        'f' => 6,
        'g' => 7,
        'h' => 8,
        'i' => 9,
        'j' => 10,
        'k' => 11,
        'l' => 12,
        'm' => 13,
        'n' => 14,
        'o' => 15,
        'p' => 16,
        'q' => 17,
        'r' => 18,
        's' => 19,
        't' => 20,
        'u' => 21,
        'v' => 22,
        'w' => 23,
        'x' => 24,
        'y' => 25,
        'z' => 26
    );
    //your sentance
    $sentance = "My name is Viswanath Polaki. And my lucky number is 33";
    $asentance = array();
    $strlen = strlen($sentance);
    //converting sentance to array and removing spaces
    for ($i = 0; $i < $strlen; $i++) {
      if ($sentance[$i] != " ")
        $asentance[] = strtolower($sentance[$i]);
    }
    $sumweights = array();
    //calculation of weights
    foreach ($asentance as $val) {
      if (key_exists($val, $weight)) {
        $sumweights[$val] += $weight[$val];
      } else {
        $sumweights['_unknown'][] = $val;
      }
    }
    ksort($sumweights);//sorting result
    echo "<pre>";
    print_r($sumweights);
    echo "</pre>";
    ?>

怎么样:

function counter($string) {
    // count the number of times each letter occurs, filtering out anything other than a-z
    $counts = array_count_values(
        str_split(
            preg_replace('/[^a-z]/iS', '', strtolower($string))
        )
    );
    // convert the counts to Caeser ciphers (a => 1, aa => 2, bb => 4, etc.)
    array_walk(
        $counts,
        function (&$value, $letter) {
            $value = $value * (ord($letter) - 96);
        }
    );
    // sum up the encodings
    $sum = array_sum($counts);
    // if there's a double i, double again
    if (preg_match('/ii/iS', $string)) {
        $sum *= 2;
    }
    return $sum;
}

测试用例

echo counter("i"); // = 9
echo counter("ii"); // = 36
echo counter("abc0"); // = 6
echo counter("aabc0"); // = 7
echo counter("aabbcc00"); // = 12
echo counter("Try to do this"); // = 173