/** * PHPredict * * A word predictor class * */ class phpredict { var $_predictionTable = array(); function phpredict() { } function parse($line) { $words = explode(' ', $line); if(count($words) > 2) { $current3WordList = array(array_shift($words), array_shift($words), array_shift($words)); $this->parse3WordList($current3WordList); if(count($words) > 0) { foreach($words as $word) { array_shift($current3WordList); array_push($current3WordList, $word); $this->parse3WordList($current3WordList); } } } } function parse3WordList($words) { if(!isset($this->_predictionTable[$words[0]])) { $this->_predictionTable[$words[0]] = array(); } if(!isset($this->_predictionTable[$words[0]][$words[1]])) { $this->_predictionTable[$words[0]][$words[1]] = array(); } if(!isset($this->_predictionTable[$words[0]][$words[1]][$words[2]])) { $this->_predictionTable[$words[0]][$words[1]][$words[2]] = 1; } else { $this->_predictionTable[$words[0]][$words[1]][$words[2]]++; } } function predict($line) { $words = explode(' ', $line); if(count($words) < 2) { return 'I need two words to predict'; } $words = array_slice($words, -2, 2); if(isset($this->_predictionTable[$words[0]])) { if(isset($this->_predictionTable[$words[0]][$words[1]])) { $maxCount = 0; foreach($this->_predictionTable[$words[0]][$words[1]] as $word => $count) { if($count > $maxCount) { $predictedWord = $word; $maxCount = $count; } } return $predictedWord; } else { return 'I dont know'; } } else { return 'I dont know'; } } function console() { $line = ''; while($line != 'exit') { echo 'PHPredict console# '; $line = trim(fgets(STDIN)); if($line == 'debug') { print_r($this); } elseif($line == 'predict') { echo 'Predict: '; $lineIn = trim(fgets(STDIN)); echo 'Predicted: ' . $lineIn . ' ' . $this->predict($lineIn); echo "\n"; } else { $this->parse($line); } } } } $phpredict = new phpredict(); $phpredict->console();