Skip to content

Instantly share code, notes, and snippets.

@puhitaku
Last active January 21, 2022 19:56
Show Gist options
  • Save puhitaku/2cb0f4cd5b38c00423bd1ee49529a8c2 to your computer and use it in GitHub Desktop.
Save puhitaku/2cb0f4cd5b38c00423bd1ee49529a8c2 to your computer and use it in GitHub Desktop.
私立PDD図書館・百科辞書を Web API にするやつ

使い方

私立PDD図書館・百科辞書のLZHファイルをapi.pyと同じディレクトリに置いて展開し、以下のような配置にしてください。

.
├── api.py
├── a
│   ├── あ
│   ├── い
│   ├── う
...
│   └── おくら
├── ha
│   ├── は
│   ├── ひ
...

依存関係を入れてください。Pythonは多分3.7以降くらいで動きます。

$ pip install flask

あとは以下のコマンドでAPIが起きます。

$ python3 api.py

リクエストを飛ばすと意味が返ってきます。

$ curl -s 'localhost:5000/%E3%81%82'
{"spelling": "", "meaning": ["【ア】\n◇[英]a-/(母音の前で)an-\n○[接頭辞]詞につけて副詞または形容詞を形成する要素。\n◎アフット(afoot):進行 中で。\nアショア(ashore):浜へ・浜に。\nアウェイク(asleep):眠らずに。\nアスリープ(asleep):眠って。", "【ア】\n◇[英]a-/(母音の前で)an-\n○[接頭辞]「非・無」を表す語形成要素。\n◎アジリア(agyria):脳回欠損。\nアタクシア(ataxia):運動失調。\nアグノージア(agnosia):失認。\nアカルキュリア(acalculia):失算。"], "error": ""}

$ curl -s 'localhost:5000/%E3%81%82' | jq .
{
  "spelling": "",
  "meaning": [
    "【ア】\n◇[英]a-/(母音の前で)an-\n○[接頭辞]詞につけて副詞または形容詞を形成する要素。\n◎アフット(afoot):進行中で。\nアショア(ashore):浜へ・浜に。\nアウェイク(asleep):眠らずに。\nアスリープ(asleep):眠って。",
    "【ア】\n◇[英]a-/(母音の前で)an-\n○[接頭辞]「非・無」を表す語形成要素。\n◎アジリア(agyria):脳回欠損。\nアタクシア(ataxia):運動失調。\nア グノージア(agnosia):失認。\nアカルキュリア(acalculia):失算。"
  ],
  "error": ""
}

ライセンス

Creative Commons CC0

import enum
import glob
import json
from dataclasses import dataclass
import flask
@dataclass(init=False)
class Item:
spelling: str
meaning: str
def parse_dictionaries():
dics = glob.glob("./**/*")
dics.sort()
parsed = []
for fn in dics:
with open(fn, "r", encoding="shift_jis", errors="ignore") as dic:
parsed += parse_items(dic)
items = dict()
for item in parsed:
meanings = items.get(item.spelling, [])
meanings.append(item.meaning)
items[item.spelling] = meanings
return items
def parse_items(dic):
class State(enum.Enum):
header = enum.auto()
spelling = enum.auto()
state = State.header
items = []
item = Item()
meaning_lines = []
for line in dic:
if state == State.header:
if line.startswith("----"):
state = State.spelling
elif state == State.spelling:
if line.startswith("----"):
continue
if line.startswith("★"):
line = line[1:]
if line.startswith("["):
line = line[line.index("]") + 1 :]
if line.startswith("\t"):
meaning_lines.append(line.strip())
else:
if meaning_lines:
item.meaning = "\n".join(meaning_lines)
items.append(item)
item = Item()
meaning_lines = []
item.spelling = line.strip()
return items
app = flask.Flask(__name__)
dictionary = parse_dictionaries()
@app.route("/<spelling>", methods=["GET"])
def get_spelling(spelling):
item = dictionary.get(spelling)
if item is None:
j = {"spelling": "", "meaning": [], "error": "not found"}
j = json.dumps(j, ensure_ascii=False)
return flask.Response(
j,
content_type="application/json; charset=utf-8",
status=404,
)
j = {"spelling": spelling, "meaning": item, "error": ""}
j = json.dumps(j, ensure_ascii=False)
return flask.Response(j, content_type="application/json; charset=utf-8", status=200)
app.run()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment