17
9

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

Pythonで漢字の情報を取得する方法(音訓読み、画数など)

Last updated at Posted at 2019-02-08

使うもの

-文字情報基盤データベースのapi
-pythonのurllib.request
-pythonのjson

Python3 コード

漢字charの読み方を辞書で返すファンクションです。

import urllib.request
import helper.directory
import json

def get_yomi(character):
    # convert character to he x unicode
    letter_a = str(character)
    decimal_a = ord(letter_a)
    hex_A = hex(decimal_a)

    # insert into api request format
    request_url = "https://mojikiban.ipa.go.jp/mji/q?UCS=*"
    request_url = request_url.replace('*', hex_A)

    req = urllib.request.Request(request_url)

    with urllib.request.urlopen(req) as res:
        body = json.load(res)

    return body['results'][0]['読み']

使い方:

print(get_yomi('蛇'))
{'音読み': ['ジャ', 'ダ', 'タ', 'シャ', 'チ', 'イ', 'ヤ', 'ジ'], '訓読み': ['へび']}

Python3のUnicode

文字情報基盤のapiはUCSキャラクターに対応してますのでunicodeをhexに変換してからリクエストURLに埋め込みます。Python3にはPython2にあったunicodeタイプはありません、strタイプを使いましょう。

jsonフォーマット

jsonから得られる辞書のフォーマット。

pprint.pprint(body)

{'count': 1,
 'find': True,
 'results': [{'IPAmj明朝フォント実装': {'フォントバージョン': '005.01', '実装したUCS': 'U+86C7'},
              'JISX0213': {'包摂区分': '0', '水準': '1', '面区点位置': '1-28-56'},
              'MJ文字図形': {'MJ文字図形バージョン': '1.0',
                         'uri': 'http://mojikiban.ipa.go.jp/MJ023408.png'},
              'MJ文字図形名': 'MJ023408',
              'UCS': {'対応するUCS': 'U+86C7', '対応カテゴリー': 'A'},
              '住基ネット統一文字コード': 'J+86C7',
              '入管外字コード': '',
              '入管正字コード': '86C7',
              '大字源': 8747,
              '大漢和': '32964',
              '大漢語林': 10023,
              '戸籍統一文字番号': '374860',
              '新大字典': 14646,
              '日本語漢字辞典': 11206,
              '漢字施策': {'人名用漢字': True, '常用漢字': True},
              '登記統一文字番号': '00374860',
              '総画数': 11,
              '読み': {'訓読み': ['へび'],
                     '音読み': ['ジャ', 'ダ', 'タ', 'シャ', 'チ', 'イ', 'ヤ', 'ジ']},
              '部首内画数': [{'内画数': 5, '部首': 142}]}],
 'status': 'success'}

17
9
1

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
17
9

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?