Skip to content

Instantly share code, notes, and snippets.

@siahr
Created February 3, 2012 11:04
Show Gist options
  • Save siahr/1729681 to your computer and use it in GitHub Desktop.
Save siahr/1729681 to your computer and use it in GitHub Desktop.
日本語WordNetの辞書(SQLite3)から同義語を取り出す。
<?php
class WN4P {
private $db;
public function __construct($dict) {
try {
$this->db = new SQLite3($dict);
} catch (Exception $e) {
throw new Exception("Unable to connect to the SQLite3 database: ".$dict);
}
}
public function close() {
$this->db->close();
}
public function __destruct() {
$this->close();
}
public function getSynonyms($word, $lang=null) {
$synonyms = array();
$words = $this->getWords($word);
$senses = $this->getSensesByWordId($words[0]['wordid']);
foreach($senses as $sens) {
$wordIdArray = $this->getSensesBySynset($sens['synset'], $lang);
foreach($wordIdArray as $wordid) {
$synonym = $this->getWord($wordid['wordid']);
$synonyms[] = $synonym[0]['lemma'];
}
}
return $synonyms;
}
private function getWords($lemma) {
return $this->getRows("select wordid from word where lemma = :lemma", array(':lemma'=>$lemma));
}
private function getWord($wordid) {
return $this->getRows("select lemma from word where wordid = :wordid", array(':wordid'=>$wordid));
}
private function getSensesByWordId($wordid) {
return $this->getRows("select synset from sense where wordid = :wordid", array(':wordid'=>$wordid));
}
private function getSensesBySynset($synset, $lang) {
if (!empty($lang)) {
return $this->getRows("select wordid from sense where synset = :synset and lang = :lang",
array(':synset'=>$synset, ':lang'=>$lang));
} else {
return $this->getRows("select wordid from sense where synset = :synset", array(':synset'=>$synset));
}
}
private function getRows($sql, $params) {
$stmt = $this->db->prepare($sql);
foreach($params as $param=>$value) {
$stmt->bindValue($param, $value);
}
$result = $stmt->execute();
$rows = array();
while($res = $result->fetchArray(SQLITE3_ASSOC)){
$rows[] = $res;
}
return $rows;
}
}
?>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment