Skip to content

Instantly share code, notes, and snippets.

@OutOfBrain
Last active April 2, 2024 10:15
Show Gist options
  • Select an option

  • Save OutOfBrain/e02ffd108367ee20f71c68b342bddb0d to your computer and use it in GitHub Desktop.

Select an option

Save OutOfBrain/e02ffd108367ee20f71c68b342bddb0d to your computer and use it in GitHub Desktop.
<?php
$dict = json_decode(file_get_contents('/Users/Sirko/Library/Application Support/plover/main.json'), true);
$dictKeys = array_keys($dict);
$inputText = strtolower('this is the first input text');
echo($inputText."\n");
$inputTextWords = explode(' ', $inputText);
for ($i = 1, $c = count($inputTextWords); $i < $c; ++$i) {
list($numWords, $foundKey) = findLongestMatch($inputTextWords);
if ($foundKey == false) {
// no match - skip to next word
$skippedWord = array_shift($inputTextWords);
echo("[".$skippedWord."] ");
continue;
}
else {
echo("$foundKey ");
}
// advance by $numWords
$inputTextWords = array_slice($inputTextWords, $numWords);
}
function findLongestMatch($inputTextWords) {
global $dict;
$foundKey = false;
for ($i = 1, $c = count($inputTextWords); $i <= $c; ++$i) {
$value = implode(' ', array_slice($inputTextWords, 0, $i));
// find all keys with that value
$keys = array_keys($dict, $value);
if (count($keys) == count($dict) || count($keys) == 0) {
// no keys found
break;
} else {
// use the shortest of the found keys
array_walk($keys, function(&$key) {
$key = str_replace('-', '', $key);
});
usort($keys, function($left, $right) {
return strlen($left) - strlen($right);
});
$foundKey = str_replace('-', '', array_shift($keys));
}
}
return [$i-1, $foundKey];
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment