fenci/app/Dictionary.php
2020-09-30 19:56:27 +08:00

86 lines
2.5 KiB
PHP

<?php
namespace app;
use CcCedict\Entry;
use CcCedict\Parser;
use Workerman\Protocols\Http\Request;
use Workerman\Protocols\Http\Response;
/**
* Class Dictionary
* The word dictionary of this website is based on CC-CEDICT.
* CC-CEDICT is a continuation of the CEDICT project started by Paul Denisowski in 1997 with the aim to provide a complete
* downloadable Chinese to English dictionary with pronunciation in pinyin for the Chinese characters.
* This website allows you to easily add new entries or correct existing entries in CC-CEDICT.
* Submitted entries will be checked and processed frequently and released for download in CEDICT format on this page.
* https://www.mdbg.net/chinese/dictionary?page=cc-cedict
* @package app
*/
class Dictionary extends Api
{
private $dictionary = [];
public function __construct()
{
if (empty($this->dictionary)) $this->initDictionary();
}
private function initDictionary()
{
$this->log("start load english dictionary ...");
$file = __DIR__ . '/files/cedict_ts.u8';
$dict_file = __DIR__ . '/files/dict.json';
if (file_exists($dict_file)) {
$this->dictionary = json_decode(file_get_contents($dict_file), true);
$this->log("loaded dictionary!");
return;
}
$parser = new Parser();
$parser->setOptions([
Entry::F_SIMPLIFIED,
Entry::F_PINYIN_DIACRITIC,
Entry::F_ENGLISH_EXPANDED,
// Entry::F_PINYIN_DIACRITIC_EXPANDED,
// Entry::F_ORIGINAL,
]);
$parser->setFilePath($file);
$dict = [];
$this->log("start parse dictionary ...");
foreach ($parser->parse() as $output) {
foreach ($output['parsedLines'] as $line) {
if(!isset($dict[$line['simplified']])){
$dict[$line['simplified']] = [];
}
$dict[$line['simplified']][] = $line;
}
}
file_put_contents($dict_file, json_encode($dict, JSON_UNESCAPED_UNICODE));
$this->dictionary = $dict;
$this->log("load english dictionary finish!");
}
/**
* @param Request $request
* @return Response
* @throws \Exception
*/
public function handle(Request $request)
{
$word = $request->get('word');
if (empty($word)) return $this->error('need query word');
if (isset($this->dictionary[$word])) {
return $this->success($this->dictionary[$word]);
}
return $this->json([]);
}
}