HizkiFW

PHP Markov Chain

May 9th, 2016
155
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
PHP 1.54 KB | None | 0 0
  1. <?php
  2. $lf = str_replace('/', '-', (isset($_REQUEST['lx'])?$_REQUEST['lx']:'en-f')) . '.json';
  3. $lex = json_decode(file_get_contents('./lexicons/' . $lf), true);
  4. $q = isset($_REQUEST['q'])?$_REQUEST['q']:'';
  5.  
  6. function nextWord($w) {
  7.     global $lex;
  8.     if(array_key_exists($w, $lex)) {
  9.         return $lex[$w][rand(0, count($lex[$w])-1)];
  10.     } else return null;
  11. }
  12. function endsWith($haystack, $needle) {
  13.     return $needle === "" || (($temp = strlen($haystack) - strlen($needle)) >= 0 && strpos($haystack, $needle, $temp) !== false);
  14. }
  15. function endsWithPunctuations($t) {
  16.     $p = str_split('(),.?!');
  17.     $r = false;
  18.     foreach($p as $n) {
  19.         if(endsWith($t, $n)) $r = true;
  20.     }
  21.     return $r;
  22. }
  23.  
  24. if(strlen($q) < 1) {
  25.     die;
  26. }
  27. $t = explode(' ', $q);
  28. if(count($t) > 1) {
  29.     $u = array_unique($t);
  30.     foreach($u as $i => $c) {
  31.         if(array_key_exists($c, $lex))
  32.             $w = $lex[$c];
  33.         else
  34.             $w = [];
  35.         for($n = 0; $n < count($t); $n++) {
  36.             if($c == $t[$n] && !endsWithPunctuations($t[$n])) {
  37.                 array_push($w, $t[$n+1]);
  38.             }
  39.         }
  40.         $lex[$c] = array_values(array_unique($w));
  41.     }
  42.     file_put_contents('./lexicons/' . $lf, strtolower(json_encode($lex)));
  43. }
  44. $s = $t[rand(0, count($t)-1)];
  45. dbg('RndWrd: ' . $s);
  46. if(array_key_exists($s, $lex)) {
  47.     dbg('Constructing setnence');
  48.     $r = $s;
  49.     $words = 0;
  50.     while(true) {
  51.         $nw = nextWord($s);
  52.         if($nw == null) break;
  53.         dbg('NxtWrd: ' . $nw);
  54.         $r .= ' ' . $nw;
  55.         $s = $nw;
  56.         if(endsWithPunctuations($nw, -1)) break;
  57.         $words++;
  58.         if($words > 50) break;
  59.     }
  60.     echo str_replace('  ', ' ', $r);
  61. } else echo 'What?';
  62. ?>
Advertisement
Add Comment
Please, Sign In to add comment